Merge branch 'Wikidata' into master.
[lhc/web/wiklou.git] / includes / EditPage.php
1 <?php
2 /**
3 * Page edition user interface.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22
23 /**
24 * The edit page/HTML interface (split from Article)
25 * The actual database and text munging is still in Article,
26 * but it should get easier to call those from alternate
27 * interfaces.
28 *
29 * EditPage cares about two distinct titles:
30 * $this->mContextTitle is the page that forms submit to, links point to,
31 * redirects go to, etc. $this->mTitle (as well as $mArticle) is the
32 * page in the database that is actually being edited. These are
33 * usually the same, but they are now allowed to be different.
34 *
35 * Surgeon General's Warning: prolonged exposure to this class is known to cause
36 * headaches, which may be fatal.
37 */
38 class EditPage {
39
40 /**
41 * Status: Article successfully updated
42 */
43 const AS_SUCCESS_UPDATE = 200;
44
45 /**
46 * Status: Article successfully created
47 */
48 const AS_SUCCESS_NEW_ARTICLE = 201;
49
50 /**
51 * Status: Article update aborted by a hook function
52 */
53 const AS_HOOK_ERROR = 210;
54
55 /**
56 * Status: A hook function returned an error
57 */
58 const AS_HOOK_ERROR_EXPECTED = 212;
59
60 /**
61 * Status: User is blocked from editting this page
62 */
63 const AS_BLOCKED_PAGE_FOR_USER = 215;
64
65 /**
66 * Status: Content too big (> $wgMaxArticleSize)
67 */
68 const AS_CONTENT_TOO_BIG = 216;
69
70 /**
71 * Status: User cannot edit? (not used)
72 */
73 const AS_USER_CANNOT_EDIT = 217;
74
75 /**
76 * Status: this anonymous user is not allowed to edit this page
77 */
78 const AS_READ_ONLY_PAGE_ANON = 218;
79
80 /**
81 * Status: this logged in user is not allowed to edit this page
82 */
83 const AS_READ_ONLY_PAGE_LOGGED = 219;
84
85 /**
86 * Status: wiki is in readonly mode (wfReadOnly() == true)
87 */
88 const AS_READ_ONLY_PAGE = 220;
89
90 /**
91 * Status: rate limiter for action 'edit' was tripped
92 */
93 const AS_RATE_LIMITED = 221;
94
95 /**
96 * Status: article was deleted while editting and param wpRecreate == false or form
97 * was not posted
98 */
99 const AS_ARTICLE_WAS_DELETED = 222;
100
101 /**
102 * Status: user tried to create this page, but is not allowed to do that
103 * ( Title->usercan('create') == false )
104 */
105 const AS_NO_CREATE_PERMISSION = 223;
106
107 /**
108 * Status: user tried to create a blank page
109 */
110 const AS_BLANK_ARTICLE = 224;
111
112 /**
113 * Status: (non-resolvable) edit conflict
114 */
115 const AS_CONFLICT_DETECTED = 225;
116
117 /**
118 * Status: no edit summary given and the user has forceeditsummary set and the user is not
119 * editting in his own userspace or talkspace and wpIgnoreBlankSummary == false
120 */
121 const AS_SUMMARY_NEEDED = 226;
122
123 /**
124 * Status: user tried to create a new section without content
125 */
126 const AS_TEXTBOX_EMPTY = 228;
127
128 /**
129 * Status: article is too big (> $wgMaxArticleSize), after merging in the new section
130 */
131 const AS_MAX_ARTICLE_SIZE_EXCEEDED = 229;
132
133 /**
134 * not used
135 */
136 const AS_OK = 230;
137
138 /**
139 * Status: WikiPage::doEdit() was unsuccessfull
140 */
141 const AS_END = 231;
142
143 /**
144 * Status: summary contained spam according to one of the regexes in $wgSummarySpamRegex
145 */
146 const AS_SPAM_ERROR = 232;
147
148 /**
149 * Status: anonymous user is not allowed to upload (User::isAllowed('upload') == false)
150 */
151 const AS_IMAGE_REDIRECT_ANON = 233;
152
153 /**
154 * Status: logged in user is not allowed to upload (User::isAllowed('upload') == false)
155 */
156 const AS_IMAGE_REDIRECT_LOGGED = 234;
157
158 /**
159 * Status: can't parse content
160 */
161 const AS_PARSE_ERROR = 240;
162
163 /**
164 * HTML id and name for the beginning of the edit form.
165 */
166 const EDITFORM_ID = 'editform';
167
168 /**
169 * @var Article
170 */
171 var $mArticle;
172
173 /**
174 * @var Title
175 */
176 var $mTitle;
177 private $mContextTitle = null;
178 var $action = 'submit';
179 var $isConflict = false;
180 var $isCssJsSubpage = false;
181 var $isCssSubpage = false;
182 var $isJsSubpage = false;
183 var $isWrongCaseCssJsPage = false;
184 var $isNew = false; // new page or new section
185 var $deletedSinceEdit;
186 var $formtype;
187 var $firsttime;
188 var $lastDelete;
189 var $mTokenOk = false;
190 var $mTokenOkExceptSuffix = false;
191 var $mTriedSave = false;
192 var $incompleteForm = false;
193 var $tooBig = false;
194 var $kblength = false;
195 var $missingComment = false;
196 var $missingSummary = false;
197 var $allowBlankSummary = false;
198 var $autoSumm = '';
199 var $hookError = '';
200 #var $mPreviewTemplates;
201
202 /**
203 * @var ParserOutput
204 */
205 var $mParserOutput;
206
207 /**
208 * Has a summary been preset using GET parameter &summary= ?
209 * @var Bool
210 */
211 var $hasPresetSummary = false;
212
213 var $mBaseRevision = false;
214 var $mShowSummaryField = true;
215
216 # Form values
217 var $save = false, $preview = false, $diff = false;
218 var $minoredit = false, $watchthis = false, $recreate = false;
219 var $textbox1 = '', $textbox2 = '', $summary = '', $nosummary = false;
220 var $edittime = '', $section = '', $sectiontitle = '', $starttime = '';
221 var $oldid = 0, $editintro = '', $scrolltop = null, $bot = true;
222 var $contentModel = null, $contentFormat = null;
223
224 # Placeholders for text injection by hooks (must be HTML)
225 # extensions should take care to _append_ to the present value
226 public $editFormPageTop = ''; // Before even the preview
227 public $editFormTextTop = '';
228 public $editFormTextBeforeContent = '';
229 public $editFormTextAfterWarn = '';
230 public $editFormTextAfterTools = '';
231 public $editFormTextBottom = '';
232 public $editFormTextAfterContent = '';
233 public $previewTextAfterContent = '';
234 public $mPreloadContent = null;
235
236 /* $didSave should be set to true whenever an article was succesfully altered. */
237 public $didSave = false;
238 public $undidRev = 0;
239
240 public $suppressIntro = false;
241
242 /**
243 * Set to true to allow editing of non-text content types.
244 *
245 * @var bool
246 */
247 public $allowNonTextContent = false;
248
249 /**
250 * @param $article Article
251 */
252 public function __construct( Article $article ) {
253 $this->mArticle = $article;
254 $this->mTitle = $article->getTitle();
255
256 $this->contentModel = $this->mTitle->getContentModel();
257
258 $handler = ContentHandler::getForModelID( $this->contentModel );
259 $this->contentFormat = $handler->getDefaultFormat();
260 }
261
262 /**
263 * @return Article
264 */
265 public function getArticle() {
266 return $this->mArticle;
267 }
268
269 /**
270 * @since 1.19
271 * @return Title
272 */
273 public function getTitle() {
274 return $this->mTitle;
275 }
276
277 /**
278 * Set the context Title object
279 *
280 * @param $title Title object or null
281 */
282 public function setContextTitle( $title ) {
283 $this->mContextTitle = $title;
284 }
285
286 /**
287 * Get the context title object.
288 * If not set, $wgTitle will be returned. This behavior might change in
289 * the future to return $this->mTitle instead.
290 *
291 * @return Title object
292 */
293 public function getContextTitle() {
294 if ( is_null( $this->mContextTitle ) ) {
295 global $wgTitle;
296 return $wgTitle;
297 } else {
298 return $this->mContextTitle;
299 }
300 }
301
302 function submit() {
303 $this->edit();
304 }
305
306 /**
307 * This is the function that gets called for "action=edit". It
308 * sets up various member variables, then passes execution to
309 * another function, usually showEditForm()
310 *
311 * The edit form is self-submitting, so that when things like
312 * preview and edit conflicts occur, we get the same form back
313 * with the extra stuff added. Only when the final submission
314 * is made and all is well do we actually save and redirect to
315 * the newly-edited page.
316 */
317 function edit() {
318 global $wgOut, $wgRequest, $wgUser;
319 // Allow extensions to modify/prevent this form or submission
320 if ( !wfRunHooks( 'AlternateEdit', array( $this ) ) ) {
321 return;
322 }
323
324 wfProfileIn( __METHOD__ );
325 wfDebug( __METHOD__ . ": enter\n" );
326
327 // If they used redlink=1 and the page exists, redirect to the main article
328 if ( $wgRequest->getBool( 'redlink' ) && $this->mTitle->exists() ) {
329 $wgOut->redirect( $this->mTitle->getFullURL() );
330 wfProfileOut( __METHOD__ );
331 return;
332 }
333
334 $this->importFormData( $wgRequest );
335 $this->firsttime = false;
336
337 if ( $this->live ) {
338 $this->livePreview();
339 wfProfileOut( __METHOD__ );
340 return;
341 }
342
343 if ( wfReadOnly() && $this->save ) {
344 // Force preview
345 $this->save = false;
346 $this->preview = true;
347 }
348
349 if ( $this->save ) {
350 $this->formtype = 'save';
351 } elseif ( $this->preview ) {
352 $this->formtype = 'preview';
353 } elseif ( $this->diff ) {
354 $this->formtype = 'diff';
355 } else { # First time through
356 $this->firsttime = true;
357 if ( $this->previewOnOpen() ) {
358 $this->formtype = 'preview';
359 } else {
360 $this->formtype = 'initial';
361 }
362 }
363
364 $permErrors = $this->getEditPermissionErrors();
365 if ( $permErrors ) {
366 wfDebug( __METHOD__ . ": User can't edit\n" );
367 // Auto-block user's IP if the account was "hard" blocked
368 $wgUser->spreadAnyEditBlock();
369
370 $this->displayPermissionsError( $permErrors );
371
372 wfProfileOut( __METHOD__ );
373 return;
374 }
375
376 wfProfileIn( __METHOD__ . "-business-end" );
377
378 $this->isConflict = false;
379 // css / js subpages of user pages get a special treatment
380 $this->isCssJsSubpage = $this->mTitle->isCssJsSubpage();
381 $this->isCssSubpage = $this->mTitle->isCssSubpage();
382 $this->isJsSubpage = $this->mTitle->isJsSubpage();
383 $this->isWrongCaseCssJsPage = $this->isWrongCaseCssJsPage();
384 $this->isNew = !$this->mTitle->exists() || $this->section == 'new';
385
386 # Show applicable editing introductions
387 if ( $this->formtype == 'initial' || $this->firsttime ) {
388 $this->showIntro();
389 }
390
391 # Attempt submission here. This will check for edit conflicts,
392 # and redundantly check for locked database, blocked IPs, etc.
393 # that edit() already checked just in case someone tries to sneak
394 # in the back door with a hand-edited submission URL.
395
396 if ( 'save' == $this->formtype ) {
397 if ( !$this->attemptSave() ) {
398 wfProfileOut( __METHOD__ . "-business-end" );
399 wfProfileOut( __METHOD__ );
400 return;
401 }
402 }
403
404 # First time through: get contents, set time for conflict
405 # checking, etc.
406 if ( 'initial' == $this->formtype || $this->firsttime ) {
407 if ( $this->initialiseForm() === false ) {
408 $this->noSuchSectionPage();
409 wfProfileOut( __METHOD__ . "-business-end" );
410 wfProfileOut( __METHOD__ );
411 return;
412 }
413 if ( !$this->mTitle->getArticleID() )
414 wfRunHooks( 'EditFormPreloadText', array( &$this->textbox1, &$this->mTitle ) );
415 else
416 wfRunHooks( 'EditFormInitialText', array( $this ) );
417 }
418
419 $this->showEditForm();
420 wfProfileOut( __METHOD__ . "-business-end" );
421 wfProfileOut( __METHOD__ );
422 }
423
424 /**
425 * @return array
426 */
427 protected function getEditPermissionErrors() {
428 global $wgUser;
429 $permErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $wgUser );
430 # Can this title be created?
431 if ( !$this->mTitle->exists() ) {
432 $permErrors = array_merge( $permErrors,
433 wfArrayDiff2( $this->mTitle->getUserPermissionsErrors( 'create', $wgUser ), $permErrors ) );
434 }
435 # Ignore some permissions errors when a user is just previewing/viewing diffs
436 $remove = array();
437 foreach ( $permErrors as $error ) {
438 if ( ( $this->preview || $this->diff ) &&
439 ( $error[0] == 'blockedtext' || $error[0] == 'autoblockedtext' ) )
440 {
441 $remove[] = $error;
442 }
443 }
444 $permErrors = wfArrayDiff2( $permErrors, $remove );
445 return $permErrors;
446 }
447
448 /**
449 * Display a permissions error page, like OutputPage::showPermissionsErrorPage(),
450 * but with the following differences:
451 * - If redlink=1, the user will be redirected to the page
452 * - If there is content to display or the error occurs while either saving,
453 * previewing or showing the difference, it will be a
454 * "View source for ..." page displaying the source code after the error message.
455 *
456 * @since 1.19
457 * @param $permErrors Array of permissions errors, as returned by
458 * Title::getUserPermissionsErrors().
459 */
460 protected function displayPermissionsError( array $permErrors ) {
461 global $wgRequest, $wgOut;
462
463 if ( $wgRequest->getBool( 'redlink' ) ) {
464 // The edit page was reached via a red link.
465 // Redirect to the article page and let them click the edit tab if
466 // they really want a permission error.
467 $wgOut->redirect( $this->mTitle->getFullUrl() );
468 return;
469 }
470
471 $content = $this->getContentObject();
472
473 # Use the normal message if there's nothing to display
474 if ( $this->firsttime && $content->isEmpty() ) {
475 $action = $this->mTitle->exists() ? 'edit' :
476 ( $this->mTitle->isTalkPage() ? 'createtalk' : 'createpage' );
477 throw new PermissionsError( $action, $permErrors );
478 }
479
480 $wgOut->setPageTitle( wfMessage( 'viewsource-title', $this->getContextTitle()->getPrefixedText() ) );
481 $wgOut->addBacklinkSubtitle( $this->getContextTitle() );
482 $wgOut->addWikiText( $wgOut->formatPermissionsErrorMessage( $permErrors, 'edit' ) );
483 $wgOut->addHTML( "<hr />\n" );
484
485 # If the user made changes, preserve them when showing the markup
486 # (This happens when a user is blocked during edit, for instance)
487 if ( !$this->firsttime ) {
488 $text = $this->textbox1;
489 $wgOut->addWikiMsg( 'viewyourtext' );
490 } else {
491 $text = $this->toEditText( $content );
492 $wgOut->addWikiMsg( 'viewsourcetext' );
493 }
494
495 $this->showTextbox( $text, 'wpTextbox1', array( 'readonly' ) );
496
497 $wgOut->addHTML( Html::rawElement( 'div', array( 'class' => 'templatesUsed' ),
498 Linker::formatTemplates( $this->getTemplates() ) ) );
499
500 if ( $this->mTitle->exists() ) {
501 $wgOut->returnToMain( null, $this->mTitle );
502 }
503 }
504
505 /**
506 * Show a read-only error
507 * Parameters are the same as OutputPage:readOnlyPage()
508 * Redirect to the article page if redlink=1
509 * @deprecated in 1.19; use displayPermissionsError() instead
510 */
511 function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
512 wfDeprecated( __METHOD__, '1.19' );
513
514 global $wgRequest, $wgOut;
515 if ( $wgRequest->getBool( 'redlink' ) ) {
516 // The edit page was reached via a red link.
517 // Redirect to the article page and let them click the edit tab if
518 // they really want a permission error.
519 $wgOut->redirect( $this->mTitle->getFullUrl() );
520 } else {
521 $wgOut->readOnlyPage( $source, $protected, $reasons, $action );
522 }
523 }
524
525 /**
526 * Should we show a preview when the edit form is first shown?
527 *
528 * @return bool
529 */
530 protected function previewOnOpen() {
531 global $wgRequest, $wgUser, $wgPreviewOnOpenNamespaces;
532 if ( $wgRequest->getVal( 'preview' ) == 'yes' ) {
533 // Explicit override from request
534 return true;
535 } elseif ( $wgRequest->getVal( 'preview' ) == 'no' ) {
536 // Explicit override from request
537 return false;
538 } elseif ( $this->section == 'new' ) {
539 // Nothing *to* preview for new sections
540 return false;
541 } elseif ( ( $wgRequest->getVal( 'preload' ) !== null || $this->mTitle->exists() ) && $wgUser->getOption( 'previewonfirst' ) ) {
542 // Standard preference behaviour
543 return true;
544 } elseif ( !$this->mTitle->exists() &&
545 isset( $wgPreviewOnOpenNamespaces[$this->mTitle->getNamespace()] ) &&
546 $wgPreviewOnOpenNamespaces[$this->mTitle->getNamespace()] )
547 {
548 // Categories are special
549 return true;
550 } else {
551 return false;
552 }
553 }
554
555 /**
556 * Checks whether the user entered a skin name in uppercase,
557 * e.g. "User:Example/Monobook.css" instead of "monobook.css"
558 *
559 * @return bool
560 */
561 protected function isWrongCaseCssJsPage() {
562 if ( $this->mTitle->isCssJsSubpage() ) {
563 $name = $this->mTitle->getSkinFromCssJsSubpage();
564 $skins = array_merge(
565 array_keys( Skin::getSkinNames() ),
566 array( 'common' )
567 );
568 return !in_array( $name, $skins )
569 && in_array( strtolower( $name ), $skins );
570 } else {
571 return false;
572 }
573 }
574
575 /**
576 * Does this EditPage class support section editing?
577 * This is used by EditPage subclasses to indicate their ui cannot handle section edits
578 *
579 * @return bool
580 */
581 protected function isSectionEditSupported() {
582 return true;
583 }
584
585 /**
586 * This function collects the form data and uses it to populate various member variables.
587 * @param $request WebRequest
588 */
589 function importFormData( &$request ) {
590 global $wgLang, $wgUser;
591
592 wfProfileIn( __METHOD__ );
593
594 # Section edit can come from either the form or a link
595 $this->section = $request->getVal( 'wpSection', $request->getVal( 'section' ) );
596
597 if ( $request->wasPosted() ) {
598 # These fields need to be checked for encoding.
599 # Also remove trailing whitespace, but don't remove _initial_
600 # whitespace from the text boxes. This may be significant formatting.
601 $this->textbox1 = $this->safeUnicodeInput( $request, 'wpTextbox1' );
602 if ( !$request->getCheck( 'wpTextbox2' ) ) {
603 // Skip this if wpTextbox2 has input, it indicates that we came
604 // from a conflict page with raw page text, not a custom form
605 // modified by subclasses
606 wfProfileIn( get_class( $this ) . "::importContentFormData" );
607 $textbox1 = $this->importContentFormData( $request );
608 if ( isset( $textbox1 ) )
609 $this->textbox1 = $textbox1;
610 wfProfileOut( get_class( $this ) . "::importContentFormData" );
611 }
612
613 # Truncate for whole multibyte characters
614 $this->summary = $wgLang->truncate( $request->getText( 'wpSummary' ), 255 );
615
616 # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
617 # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
618 # section titles.
619 $this->summary = preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary );
620
621 # Treat sectiontitle the same way as summary.
622 # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
623 # currently doing double duty as both edit summary and section title. Right now this
624 # is just to allow API edits to work around this limitation, but this should be
625 # incorporated into the actual edit form when EditPage is rewritten (Bugs 18654, 26312).
626 $this->sectiontitle = $wgLang->truncate( $request->getText( 'wpSectionTitle' ), 255 );
627 $this->sectiontitle = preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle );
628
629 $this->edittime = $request->getVal( 'wpEdittime' );
630 $this->starttime = $request->getVal( 'wpStarttime' );
631
632 $this->scrolltop = $request->getIntOrNull( 'wpScrolltop' );
633
634 if ( $this->textbox1 === '' && $request->getVal( 'wpTextbox1' ) === null ) {
635 // wpTextbox1 field is missing, possibly due to being "too big"
636 // according to some filter rules such as Suhosin's setting for
637 // suhosin.request.max_value_length (d'oh)
638 $this->incompleteForm = true;
639 } else {
640 // edittime should be one of our last fields; if it's missing,
641 // the submission probably broke somewhere in the middle.
642 $this->incompleteForm = is_null( $this->edittime );
643 }
644 if ( $this->incompleteForm ) {
645 # If the form is incomplete, force to preview.
646 wfDebug( __METHOD__ . ": Form data appears to be incomplete\n" );
647 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
648 $this->preview = true;
649 } else {
650 /* Fallback for live preview */
651 $this->preview = $request->getCheck( 'wpPreview' ) || $request->getCheck( 'wpLivePreview' );
652 $this->diff = $request->getCheck( 'wpDiff' );
653
654 // Remember whether a save was requested, so we can indicate
655 // if we forced preview due to session failure.
656 $this->mTriedSave = !$this->preview;
657
658 if ( $this->tokenOk( $request ) ) {
659 # Some browsers will not report any submit button
660 # if the user hits enter in the comment box.
661 # The unmarked state will be assumed to be a save,
662 # if the form seems otherwise complete.
663 wfDebug( __METHOD__ . ": Passed token check.\n" );
664 } elseif ( $this->diff ) {
665 # Failed token check, but only requested "Show Changes".
666 wfDebug( __METHOD__ . ": Failed token check; Show Changes requested.\n" );
667 } else {
668 # Page might be a hack attempt posted from
669 # an external site. Preview instead of saving.
670 wfDebug( __METHOD__ . ": Failed token check; forcing preview\n" );
671 $this->preview = true;
672 }
673 }
674 $this->save = !$this->preview && !$this->diff;
675 if ( !preg_match( '/^\d{14}$/', $this->edittime ) ) {
676 $this->edittime = null;
677 }
678
679 if ( !preg_match( '/^\d{14}$/', $this->starttime ) ) {
680 $this->starttime = null;
681 }
682
683 $this->recreate = $request->getCheck( 'wpRecreate' );
684
685 $this->minoredit = $request->getCheck( 'wpMinoredit' );
686 $this->watchthis = $request->getCheck( 'wpWatchthis' );
687
688 # Don't force edit summaries when a user is editing their own user or talk page
689 if ( ( $this->mTitle->mNamespace == NS_USER || $this->mTitle->mNamespace == NS_USER_TALK ) &&
690 $this->mTitle->getText() == $wgUser->getName() )
691 {
692 $this->allowBlankSummary = true;
693 } else {
694 $this->allowBlankSummary = $request->getBool( 'wpIgnoreBlankSummary' ) || !$wgUser->getOption( 'forceeditsummary' );
695 }
696
697 $this->autoSumm = $request->getText( 'wpAutoSummary' );
698 } else {
699 # Not a posted form? Start with nothing.
700 wfDebug( __METHOD__ . ": Not a posted form.\n" );
701 $this->textbox1 = '';
702 $this->summary = '';
703 $this->sectiontitle = '';
704 $this->edittime = '';
705 $this->starttime = wfTimestampNow();
706 $this->edit = false;
707 $this->preview = false;
708 $this->save = false;
709 $this->diff = false;
710 $this->minoredit = false;
711 $this->watchthis = $request->getBool( 'watchthis', false ); // Watch may be overriden by request parameters
712 $this->recreate = false;
713
714 // When creating a new section, we can preload a section title by passing it as the
715 // preloadtitle parameter in the URL (Bug 13100)
716 if ( $this->section == 'new' && $request->getVal( 'preloadtitle' ) ) {
717 $this->sectiontitle = $request->getVal( 'preloadtitle' );
718 // Once wpSummary isn't being use for setting section titles, we should delete this.
719 $this->summary = $request->getVal( 'preloadtitle' );
720 }
721 elseif ( $this->section != 'new' && $request->getVal( 'summary' ) ) {
722 $this->summary = $request->getText( 'summary' );
723 if ( $this->summary !== '' ) {
724 $this->hasPresetSummary = true;
725 }
726 }
727
728 if ( $request->getVal( 'minor' ) ) {
729 $this->minoredit = true;
730 }
731 }
732
733 $this->oldid = $request->getInt( 'oldid' );
734
735 $this->bot = $request->getBool( 'bot', true );
736 $this->nosummary = $request->getBool( 'nosummary' );
737
738 $content_handler = ContentHandler::getForTitle( $this->mTitle );
739 $this->contentModel = $request->getText( 'model', $content_handler->getModelID() ); #may be overridden by revision
740 $this->contentFormat = $request->getText( 'format', $content_handler->getDefaultFormat() ); #may be overridden by revision
741
742 #TODO: check if the desired model is allowed in this namespace, and if a transition from the page's current model to the new model is allowed
743 #TODO: check if the desired content model supports the given content format!
744
745 $this->live = $request->getCheck( 'live' );
746 $this->editintro = $request->getText( 'editintro',
747 // Custom edit intro for new sections
748 $this->section === 'new' ? 'MediaWiki:addsection-editintro' : '' );
749
750 // Allow extensions to modify form data
751 wfRunHooks( 'EditPage::importFormData', array( $this, $request ) );
752
753 wfProfileOut( __METHOD__ );
754 }
755
756 /**
757 * Subpage overridable method for extracting the page content data from the
758 * posted form to be placed in $this->textbox1, if using customized input
759 * this method should be overrided and return the page text that will be used
760 * for saving, preview parsing and so on...
761 *
762 * @param $request WebRequest
763 */
764 protected function importContentFormData( &$request ) {
765 return; // Don't do anything, EditPage already extracted wpTextbox1
766 }
767
768 /**
769 * Initialise form fields in the object
770 * Called on the first invocation, e.g. when a user clicks an edit link
771 * @return bool -- if the requested section is valid
772 */
773 function initialiseForm() {
774 global $wgUser;
775 $this->edittime = $this->mArticle->getTimestamp();
776
777 $content = $this->getContentObject( false ); #TODO: track content object?!
778 $this->textbox1 = $this->toEditText( $content );
779
780 // activate checkboxes if user wants them to be always active
781 # Sort out the "watch" checkbox
782 if ( $wgUser->getOption( 'watchdefault' ) ) {
783 # Watch all edits
784 $this->watchthis = true;
785 } elseif ( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle->exists() ) {
786 # Watch creations
787 $this->watchthis = true;
788 } elseif ( $wgUser->isWatched( $this->mTitle ) ) {
789 # Already watched
790 $this->watchthis = true;
791 }
792 if ( $wgUser->getOption( 'minordefault' ) && !$this->isNew ) {
793 $this->minoredit = true;
794 }
795 if ( $this->textbox1 === false ) {
796 return false;
797 }
798 wfProxyCheck();
799 return true;
800 }
801
802 /**
803 * Fetch initial editing page content.
804 *
805 * @param $def_text string
806 * @return mixed string on success, $def_text for invalid sections
807 * @private
808 * @deprecated since 1.21
809 */
810 function getContent( $def_text = false ) {
811 wfDeprecated( __METHOD__, '1.21' );
812
813 if ( $def_text !== null && $def_text !== false && $def_text !== '' ) {
814 $def_content = $this->toEditContent( $def_text );
815 } else {
816 $def_content = false;
817 }
818
819 $content = $this->getContentObject( $def_content );
820
821 // Note: EditPage should only be used with text based content anyway.
822 return $this->toEditText( $content );
823 }
824
825 /**
826 * @param Content|false $def_content The default value to return
827 *
828 * @return mixed Content on success, $def_content for invalid sections
829 *
830 * @since 1.21
831 */
832 protected function getContentObject( $def_content = null ) {
833 global $wgOut, $wgRequest;
834
835 wfProfileIn( __METHOD__ );
836
837 $content = false;
838
839 // For message page not locally set, use the i18n message.
840 // For other non-existent articles, use preload text if any.
841 if ( !$this->mTitle->exists() || $this->section == 'new' ) {
842 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI && $this->section != 'new' ) {
843 # If this is a system message, get the default text.
844 $msg = $this->mTitle->getDefaultMessageText();
845
846 $content = $this->toEditContent( $msg );
847 }
848 if ( $content === false ) {
849 # If requested, preload some text.
850 $preload = $wgRequest->getVal( 'preload',
851 // Custom preload text for new sections
852 $this->section === 'new' ? 'MediaWiki:addsection-preload' : '' );
853
854 $content = $this->getPreloadedContent( $preload );
855 }
856 // For existing pages, get text based on "undo" or section parameters.
857 } else {
858 if ( $this->section != '' ) {
859 // Get section edit text (returns $def_text for invalid sections)
860 $orig = $this->getOriginalContent();
861 $content = $orig ? $orig->getSection( $this->section ) : null;
862
863 if ( !$content ) $content = $def_content;
864 } else {
865 $undoafter = $wgRequest->getInt( 'undoafter' );
866 $undo = $wgRequest->getInt( 'undo' );
867
868 if ( $undo > 0 && $undoafter > 0 ) {
869 if ( $undo < $undoafter ) {
870 # If they got undoafter and undo round the wrong way, switch them
871 list( $undo, $undoafter ) = array( $undoafter, $undo );
872 }
873
874 $undorev = Revision::newFromId( $undo );
875 $oldrev = Revision::newFromId( $undoafter );
876
877 # Sanity check, make sure it's the right page,
878 # the revisions exist and they were not deleted.
879 # Otherwise, $content will be left as-is.
880 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
881 $undorev->getPage() == $oldrev->getPage() &&
882 $undorev->getPage() == $this->mTitle->getArticleID() &&
883 !$undorev->isDeleted( Revision::DELETED_TEXT ) &&
884 !$oldrev->isDeleted( Revision::DELETED_TEXT ) ) {
885
886 $content = $this->mArticle->getUndoContent( $undorev, $oldrev );
887
888 if ( $content === false ) {
889 # Warn the user that something went wrong
890 $undoMsg = 'failure';
891 } else {
892 # Inform the user of our success and set an automatic edit summary
893 $undoMsg = 'success';
894
895 # If we just undid one rev, use an autosummary
896 $firstrev = $oldrev->getNext();
897 if ( $firstrev && $firstrev->getId() == $undo ) {
898 $undoSummary = wfMessage( 'undo-summary', $undo, $undorev->getUserText() )->inContentLanguage()->text();
899 if ( $this->summary === '' ) {
900 $this->summary = $undoSummary;
901 } else {
902 $this->summary = $undoSummary . wfMessage( 'colon-separator' )
903 ->inContentLanguage()->text() . $this->summary;
904 }
905 $this->undidRev = $undo;
906 }
907 $this->formtype = 'diff';
908 }
909 } else {
910 // Failed basic sanity checks.
911 // Older revisions may have been removed since the link
912 // was created, or we may simply have got bogus input.
913 $undoMsg = 'norev';
914 }
915
916 $class = ( $undoMsg == 'success' ? '' : 'error ' ) . "mw-undo-{$undoMsg}";
917 $this->editFormPageTop .= $wgOut->parse( "<div class=\"{$class}\">" .
918 wfMessage( 'undo-' . $undoMsg )->plain() . '</div>', true, /* interface */true );
919 }
920
921 if ( $content === false ) {
922 $content = $this->getOriginalContent();
923 }
924 }
925 }
926
927 wfProfileOut( __METHOD__ );
928 return $content;
929 }
930
931 /**
932 * Get the content of the wanted revision, without section extraction.
933 *
934 * The result of this function can be used to compare user's input with
935 * section replaced in its context (using WikiPage::replaceSection())
936 * to the original text of the edit.
937 *
938 * This difers from Article::getContent() that when a missing revision is
939 * encountered the result will be an empty string and not the
940 * 'missing-revision' message.
941 *
942 * @since 1.19
943 * @return string
944 */
945 private function getOriginalContent() {
946 if ( $this->section == 'new' ) {
947 return $this->getCurrentContent();
948 }
949 $revision = $this->mArticle->getRevisionFetched();
950 if ( $revision === null ) {
951 if ( !$this->contentModel ) $this->contentModel = $this->getTitle()->getContentModel();
952 $handler = ContentHandler::getForModelID( $this->contentModel );
953
954 return $handler->makeEmptyContent();
955 }
956 $content = $revision->getContent();
957 return $content;
958 }
959
960 /**
961 * Get the current content of the page. This is basically similar to
962 * WikiPage::getContent( Revision::RAW ) except that when the page doesn't exist an empty
963 * content object is returned instead of null.
964 *
965 * @since 1.21
966 * @return Content
967 */
968 protected function getCurrentContent() {
969 $rev = $this->mArticle->getRevision();
970 $content = $rev ? $rev->getContent( Revision::RAW ) : null;
971
972 if ( $content === false || $content === null ) {
973 if ( !$this->contentModel ) $this->contentModel = $this->getTitle()->getContentModel();
974 $handler = ContentHandler::getForModelID( $this->contentModel );
975
976 return $handler->makeEmptyContent();
977 } else {
978 # nasty side-effect, but needed for consistency
979 $this->contentModel = $rev->getContentModel();
980 $this->contentFormat = $rev->getContentFormat();
981
982 return $content;
983 }
984 }
985
986
987 /**
988 * Use this method before edit() to preload some text into the edit box
989 *
990 * @param $text string
991 * @deprecated since 1.21
992 */
993 public function setPreloadedText( $text ) {
994 wfDeprecated( __METHOD__, "1.21" );
995
996 $content = $this->toEditContent( $text );
997
998 $this->setPreloadedContent( $content );
999 }
1000
1001 /**
1002 * Use this method before edit() to preload some content into the edit box
1003 *
1004 * @param $content Content
1005 *
1006 * @since 1.21
1007 */
1008 public function setPreloadedContent( Content $content ) {
1009 $this->mPreloadedContent = $content;
1010 }
1011
1012 /**
1013 * Get the contents to be preloaded into the box, either set by
1014 * an earlier setPreloadText() or by loading the given page.
1015 *
1016 * @param $preload String: representing the title to preload from.
1017 *
1018 * @return String
1019 *
1020 * @deprecated since 1.21, use getPreloadedContent() instead
1021 */
1022 protected function getPreloadedText( $preload ) {
1023 wfDeprecated( __METHOD__, "1.21" );
1024
1025 $content = $this->getPreloadedContent( $preload );
1026 $text = $this->toEditText( $content );
1027
1028 return $text;
1029 }
1030
1031 /**
1032 * Get the contents to be preloaded into the box, either set by
1033 * an earlier setPreloadText() or by loading the given page.
1034 *
1035 * @param $preload String: representing the title to preload from.
1036 *
1037 * @return Content
1038 *
1039 * @since 1.21
1040 */
1041 protected function getPreloadedContent( $preload ) {
1042 global $wgUser;
1043
1044 if ( !empty( $this->mPreloadContent ) ) {
1045 return $this->mPreloadContent;
1046 }
1047
1048 $handler = ContentHandler::getForTitle( $this->getTitle() );
1049
1050 if ( $preload === '' ) {
1051 return $handler->makeEmptyContent();
1052 }
1053
1054 $title = Title::newFromText( $preload );
1055 # Check for existence to avoid getting MediaWiki:Noarticletext
1056 if ( $title === null || !$title->exists() || !$title->userCan( 'read' ) ) {
1057 return $handler->makeEmptyContent();
1058 }
1059
1060 $page = WikiPage::factory( $title );
1061 if ( $page->isRedirect() ) {
1062 $title = $page->getRedirectTarget();
1063 # Same as before
1064 if ( $title === null || !$title->exists() || !$title->userCan( 'read' ) ) {
1065 return $handler->makeEmptyContent();
1066 }
1067 $page = WikiPage::factory( $title );
1068 }
1069
1070 $parserOptions = ParserOptions::newFromUser( $wgUser );
1071 $content = $page->getContent( Revision::RAW );
1072
1073 return $content->preloadTransform( $title, $parserOptions );
1074 }
1075
1076 /**
1077 * Make sure the form isn't faking a user's credentials.
1078 *
1079 * @param $request WebRequest
1080 * @return bool
1081 * @private
1082 */
1083 function tokenOk( &$request ) {
1084 global $wgUser;
1085 $token = $request->getVal( 'wpEditToken' );
1086 $this->mTokenOk = $wgUser->matchEditToken( $token );
1087 $this->mTokenOkExceptSuffix = $wgUser->matchEditTokenNoSuffix( $token );
1088 return $this->mTokenOk;
1089 }
1090
1091 /**
1092 * Attempt submission
1093 * @return bool false if output is done, true if the rest of the form should be displayed
1094 */
1095 function attemptSave() {
1096 global $wgUser, $wgOut;
1097
1098 $resultDetails = false;
1099 # Allow bots to exempt some edits from bot flagging
1100 $bot = $wgUser->isAllowed( 'bot' ) && $this->bot;
1101 $status = $this->internalAttemptSave( $resultDetails, $bot );
1102 // FIXME: once the interface for internalAttemptSave() is made nicer, this should use the message in $status
1103 if ( $status->value == self::AS_SUCCESS_UPDATE || $status->value == self::AS_SUCCESS_NEW_ARTICLE ) {
1104 $this->didSave = true;
1105 }
1106
1107 switch ( $status->value ) {
1108 case self::AS_HOOK_ERROR_EXPECTED:
1109 case self::AS_CONTENT_TOO_BIG:
1110 case self::AS_ARTICLE_WAS_DELETED:
1111 case self::AS_CONFLICT_DETECTED:
1112 case self::AS_SUMMARY_NEEDED:
1113 case self::AS_TEXTBOX_EMPTY:
1114 case self::AS_MAX_ARTICLE_SIZE_EXCEEDED:
1115 case self::AS_END:
1116 return true;
1117
1118 case self::AS_HOOK_ERROR:
1119 return false;
1120
1121 case self::AS_PARSE_ERROR:
1122 $wgOut->addWikiText( '<div class="error">' . $status->getWikiText() . '</div>');
1123 return true;
1124
1125 case self::AS_SUCCESS_NEW_ARTICLE:
1126 $query = $resultDetails['redirect'] ? 'redirect=no' : '';
1127 $anchor = isset ( $resultDetails['sectionanchor'] ) ? $resultDetails['sectionanchor'] : '';
1128 $wgOut->redirect( $this->mTitle->getFullURL( $query ) . $anchor );
1129 return false;
1130
1131 case self::AS_SUCCESS_UPDATE:
1132 $extraQuery = '';
1133 $sectionanchor = $resultDetails['sectionanchor'];
1134
1135 // Give extensions a chance to modify URL query on update
1136 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this->mArticle, &$sectionanchor, &$extraQuery ) );
1137
1138 if ( $resultDetails['redirect'] ) {
1139 if ( $extraQuery == '' ) {
1140 $extraQuery = 'redirect=no';
1141 } else {
1142 $extraQuery = 'redirect=no&' . $extraQuery;
1143 }
1144 }
1145 $wgOut->redirect( $this->mTitle->getFullURL( $extraQuery ) . $sectionanchor );
1146 return false;
1147
1148 case self::AS_BLANK_ARTICLE:
1149 $wgOut->redirect( $this->getContextTitle()->getFullURL() );
1150 return false;
1151
1152 case self::AS_SPAM_ERROR:
1153 $this->spamPageWithContent( $resultDetails['spam'] );
1154 return false;
1155
1156 case self::AS_BLOCKED_PAGE_FOR_USER:
1157 throw new UserBlockedError( $wgUser->getBlock() );
1158
1159 case self::AS_IMAGE_REDIRECT_ANON:
1160 case self::AS_IMAGE_REDIRECT_LOGGED:
1161 throw new PermissionsError( 'upload' );
1162
1163 case self::AS_READ_ONLY_PAGE_ANON:
1164 case self::AS_READ_ONLY_PAGE_LOGGED:
1165 throw new PermissionsError( 'edit' );
1166
1167 case self::AS_READ_ONLY_PAGE:
1168 throw new ReadOnlyError;
1169
1170 case self::AS_RATE_LIMITED:
1171 throw new ThrottledError();
1172
1173 case self::AS_NO_CREATE_PERMISSION:
1174 $permission = $this->mTitle->isTalkPage() ? 'createtalk' : 'createpage';
1175 throw new PermissionsError( $permission );
1176
1177 default:
1178 // We don't recognize $status->value. The only way that can happen
1179 // is if an extension hook aborted from inside ArticleSave.
1180 // Render the status object into $this->hookError
1181 // FIXME this sucks, we should just use the Status object throughout
1182 $this->hookError = '<div class="error">' . $status->getWikitext() .
1183 '</div>';
1184 return true;
1185 }
1186 }
1187
1188 /**
1189 * Attempt submission (no UI)
1190 *
1191 * @param $result
1192 * @param $bot bool
1193 *
1194 * @return Status object, possibly with a message, but always with one of the AS_* constants in $status->value,
1195 *
1196 * FIXME: This interface is TERRIBLE, but hard to get rid of due to various error display idiosyncrasies. There are
1197 * also lots of cases where error metadata is set in the object and retrieved later instead of being returned, e.g.
1198 * AS_CONTENT_TOO_BIG and AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some time.
1199 */
1200 function internalAttemptSave( &$result, $bot = false ) {
1201 global $wgUser, $wgRequest, $wgParser, $wgMaxArticleSize;
1202
1203 $status = Status::newGood();
1204
1205 wfProfileIn( __METHOD__ );
1206 wfProfileIn( __METHOD__ . '-checks' );
1207
1208 if ( !wfRunHooks( 'EditPage::attemptSave', array( $this ) ) ) {
1209 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1210 $status->fatal( 'hookaborted' );
1211 $status->value = self::AS_HOOK_ERROR;
1212 wfProfileOut( __METHOD__ . '-checks' );
1213 wfProfileOut( __METHOD__ );
1214 return $status;
1215 }
1216
1217 try {
1218 # Construct Content object
1219 $textbox_content = $this->toEditContent( $this->textbox1 );
1220 } catch (MWContentSerializationException $ex) {
1221 $status->fatal( 'content-failed-to-parse', $this->contentModel, $this->contentFormat, $ex->getMessage() );
1222 $status->value = self::AS_PARSE_ERROR;
1223 wfProfileOut( __METHOD__ );
1224 return $status;
1225 }
1226
1227 # Check image redirect
1228 if ( $this->mTitle->getNamespace() == NS_FILE &&
1229 $textbox_content->isRedirect() &&
1230 !$wgUser->isAllowed( 'upload' ) ) {
1231 $code = $wgUser->isAnon() ? self::AS_IMAGE_REDIRECT_ANON : self::AS_IMAGE_REDIRECT_LOGGED;
1232 $status->setResult( false, $code );
1233
1234 wfProfileOut( __METHOD__ . '-checks' );
1235 wfProfileOut( __METHOD__ );
1236
1237 return $status;
1238 }
1239
1240 # Check for spam
1241 $match = self::matchSummarySpamRegex( $this->summary );
1242 if ( $match === false ) {
1243 $match = self::matchSpamRegex( $this->textbox1 );
1244 }
1245 if ( $match !== false ) {
1246 $result['spam'] = $match;
1247 $ip = $wgRequest->getIP();
1248 $pdbk = $this->mTitle->getPrefixedDBkey();
1249 $match = str_replace( "\n", '', $match );
1250 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1251 $status->fatal( 'spamprotectionmatch', $match );
1252 $status->value = self::AS_SPAM_ERROR;
1253 wfProfileOut( __METHOD__ . '-checks' );
1254 wfProfileOut( __METHOD__ );
1255 return $status;
1256 }
1257 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1, $this->section, &$this->hookError, $this->summary ) ) ) {
1258 # Error messages etc. could be handled within the hook...
1259 $status->fatal( 'hookaborted' );
1260 $status->value = self::AS_HOOK_ERROR;
1261 wfProfileOut( __METHOD__ . '-checks' );
1262 wfProfileOut( __METHOD__ );
1263 return $status;
1264 } elseif ( $this->hookError != '' ) {
1265 # ...or the hook could be expecting us to produce an error
1266 $status->fatal( 'hookaborted' );
1267 $status->value = self::AS_HOOK_ERROR_EXPECTED;
1268 wfProfileOut( __METHOD__ . '-checks' );
1269 wfProfileOut( __METHOD__ );
1270 return $status;
1271 }
1272
1273 if ( $wgUser->isBlockedFrom( $this->mTitle, false ) ) {
1274 // Auto-block user's IP if the account was "hard" blocked
1275 $wgUser->spreadAnyEditBlock();
1276 # Check block state against master, thus 'false'.
1277 $status->setResult( false, self::AS_BLOCKED_PAGE_FOR_USER );
1278 wfProfileOut( __METHOD__ . '-checks' );
1279 wfProfileOut( __METHOD__ );
1280 return $status;
1281 }
1282
1283 $this->kblength = (int)( strlen( $this->textbox1 ) / 1024 );
1284 if ( $this->kblength > $wgMaxArticleSize ) {
1285 // Error will be displayed by showEditForm()
1286 $this->tooBig = true;
1287 $status->setResult( false, self::AS_CONTENT_TOO_BIG );
1288 wfProfileOut( __METHOD__ . '-checks' );
1289 wfProfileOut( __METHOD__ );
1290 return $status;
1291 }
1292
1293 if ( !$wgUser->isAllowed( 'edit' ) ) {
1294 if ( $wgUser->isAnon() ) {
1295 $status->setResult( false, self::AS_READ_ONLY_PAGE_ANON );
1296 wfProfileOut( __METHOD__ . '-checks' );
1297 wfProfileOut( __METHOD__ );
1298 return $status;
1299 } else {
1300 $status->fatal( 'readonlytext' );
1301 $status->value = self::AS_READ_ONLY_PAGE_LOGGED;
1302 wfProfileOut( __METHOD__ . '-checks' );
1303 wfProfileOut( __METHOD__ );
1304 return $status;
1305 }
1306 }
1307
1308 if ( wfReadOnly() ) {
1309 $status->fatal( 'readonlytext' );
1310 $status->value = self::AS_READ_ONLY_PAGE;
1311 wfProfileOut( __METHOD__ . '-checks' );
1312 wfProfileOut( __METHOD__ );
1313 return $status;
1314 }
1315 if ( $wgUser->pingLimiter() ) {
1316 $status->fatal( 'actionthrottledtext' );
1317 $status->value = self::AS_RATE_LIMITED;
1318 wfProfileOut( __METHOD__ . '-checks' );
1319 wfProfileOut( __METHOD__ );
1320 return $status;
1321 }
1322
1323 # If the article has been deleted while editing, don't save it without
1324 # confirmation
1325 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate ) {
1326 $status->setResult( false, self::AS_ARTICLE_WAS_DELETED );
1327 wfProfileOut( __METHOD__ . '-checks' );
1328 wfProfileOut( __METHOD__ );
1329 return $status;
1330 }
1331
1332 wfProfileOut( __METHOD__ . '-checks' );
1333
1334 # Load the page data from the master. If anything changes in the meantime,
1335 # we detect it by using page_latest like a token in a 1 try compare-and-swap.
1336 $this->mArticle->loadPageData( 'fromdbmaster' );
1337 $new = !$this->mArticle->exists();
1338
1339 if ( $new ) {
1340 // Late check for create permission, just in case *PARANOIA*
1341 if ( !$this->mTitle->userCan( 'create' ) ) {
1342 $status->fatal( 'nocreatetext' );
1343 $status->value = self::AS_NO_CREATE_PERMISSION;
1344 wfDebug( __METHOD__ . ": no create permission\n" );
1345 wfProfileOut( __METHOD__ );
1346 return $status;
1347 }
1348
1349 # Don't save a new article if it's blank.
1350 if ( $this->textbox1 == '' ) {
1351 $status->setResult( false, self::AS_BLANK_ARTICLE );
1352 wfProfileOut( __METHOD__ );
1353 return $status;
1354 }
1355
1356 // Run post-section-merge edit filter
1357 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $this->textbox1, &$this->hookError, $this->summary ) ) ) {
1358 # Error messages etc. could be handled within the hook...
1359 $status->fatal( 'hookaborted' );
1360 $status->value = self::AS_HOOK_ERROR;
1361 wfProfileOut( __METHOD__ );
1362 return $status;
1363 } elseif ( $this->hookError != '' ) {
1364 # ...or the hook could be expecting us to produce an error
1365 $status->fatal( 'hookaborted' );
1366 $status->value = self::AS_HOOK_ERROR_EXPECTED;
1367 wfProfileOut( __METHOD__ );
1368 return $status;
1369 }
1370
1371 $content = $textbox_content;
1372
1373 $result['sectionanchor'] = '';
1374 if ( $this->section == 'new' ) {
1375 if ( $this->sectiontitle !== '' ) {
1376 // Insert the section title above the content.
1377 $content = $content->addSectionHeader( $this->sectiontitle );
1378
1379 // Jump to the new section
1380 $result['sectionanchor'] = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle );
1381
1382 // If no edit summary was specified, create one automatically from the section
1383 // title and have it link to the new section. Otherwise, respect the summary as
1384 // passed.
1385 if ( $this->summary === '' ) {
1386 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle );
1387 $this->summary = wfMessage( 'newsectionsummary', $cleanSectionTitle )
1388 ->inContentLanguage()->text() ;
1389 }
1390 } elseif ( $this->summary !== '' ) {
1391 // Insert the section title above the content.
1392 $content = $content->addSectionHeader( $this->summary );
1393
1394 // Jump to the new section
1395 $result['sectionanchor'] = $wgParser->guessLegacySectionNameFromWikiText( $this->summary );
1396
1397 // Create a link to the new section from the edit summary.
1398 $cleanSummary = $wgParser->stripSectionName( $this->summary );
1399 $this->summary = wfMessage( 'newsectionsummary', $cleanSummary )
1400 ->inContentLanguage()->text();
1401 }
1402 }
1403
1404 $status->value = self::AS_SUCCESS_NEW_ARTICLE;
1405
1406 } else { # not $new
1407
1408 # Article exists. Check for edit conflict.
1409
1410 $this->mArticle->clear(); # Force reload of dates, etc.
1411 $timestamp = $this->mArticle->getTimestamp();
1412
1413 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
1414
1415 if ( $timestamp != $this->edittime ) {
1416 $this->isConflict = true;
1417 if ( $this->section == 'new' ) {
1418 if ( $this->mArticle->getUserText() == $wgUser->getName() &&
1419 $this->mArticle->getComment() == $this->summary ) {
1420 // Probably a duplicate submission of a new comment.
1421 // This can happen when squid resends a request after
1422 // a timeout but the first one actually went through.
1423 wfDebug( __METHOD__ . ": duplicate new section submission; trigger edit conflict!\n" );
1424 } else {
1425 // New comment; suppress conflict.
1426 $this->isConflict = false;
1427 wfDebug( __METHOD__ . ": conflict suppressed; new section\n" );
1428 }
1429 } elseif ( $this->section == '' && Revision::userWasLastToEdit( DB_MASTER, $this->mTitle->getArticleID(),
1430 $wgUser->getId(), $this->edittime ) ) {
1431 # Suppress edit conflict with self, except for section edits where merging is required.
1432 wfDebug( __METHOD__ . ": Suppressing edit conflict, same user.\n" );
1433 $this->isConflict = false;
1434 }
1435 }
1436
1437 // If sectiontitle is set, use it, otherwise use the summary as the section title (for
1438 // backwards compatibility with old forms/bots).
1439 if ( $this->sectiontitle !== '' ) {
1440 $sectionTitle = $this->sectiontitle;
1441 } else {
1442 $sectionTitle = $this->summary;
1443 }
1444
1445 $content = null;
1446
1447 if ( $this->isConflict ) {
1448 wfDebug( __METHOD__ . ": conflict! getting section '{$this->section}' for time '{$this->edittime}'"
1449 . " (article time '{$timestamp}')\n" );
1450
1451 $content = $this->mArticle->replaceSectionContent( $this->section, $textbox_content, $sectionTitle, $this->edittime );
1452 } else {
1453 wfDebug( __METHOD__ . ": getting section '{$this->section}'\n" );
1454 $content = $this->mArticle->replaceSectionContent( $this->section, $textbox_content, $sectionTitle );
1455 }
1456
1457 if ( is_null( $content ) ) {
1458 wfDebug( __METHOD__ . ": activating conflict; section replace failed.\n" );
1459 $this->isConflict = true;
1460 $content = $textbox_content; // do not try to merge here!
1461 } elseif ( $this->isConflict ) {
1462 # Attempt merge
1463 if ( $this->mergeChangesIntoContent( $textbox_content ) ) {
1464 // Successful merge! Maybe we should tell the user the good news?
1465 $this->isConflict = false;
1466 $content = $textbox_content;
1467 wfDebug( __METHOD__ . ": Suppressing edit conflict, successful merge.\n" );
1468 } else {
1469 $this->section = '';
1470 #$this->textbox1 = $text; #redundant, nothing to do here?
1471 wfDebug( __METHOD__ . ": Keeping edit conflict, failed merge.\n" );
1472 }
1473 }
1474
1475 if ( $this->isConflict ) {
1476 $status->setResult( false, self::AS_CONFLICT_DETECTED );
1477 wfProfileOut( __METHOD__ );
1478 return $status;
1479 }
1480
1481 // Run post-section-merge edit filter
1482 $hook_args = array( $this, $content, &$this->hookError, $this->summary );
1483
1484 if ( !ContentHandler::runLegacyHooks( 'EditFilterMerged', $hook_args )
1485 || !wfRunHooks( 'EditFilterMergedContent', $hook_args ) ) {
1486 # Error messages etc. could be handled within the hook...
1487 $status->fatal( 'hookaborted' );
1488 $status->value = self::AS_HOOK_ERROR;
1489 wfProfileOut( __METHOD__ );
1490 return $status;
1491 } elseif ( $this->hookError != '' ) {
1492 # ...or the hook could be expecting us to produce an error
1493 $status->fatal( 'hookaborted' );
1494 $status->value = self::AS_HOOK_ERROR_EXPECTED;
1495 wfProfileOut( __METHOD__ );
1496 return $status;
1497 }
1498
1499 # Handle the user preference to force summaries here, but not for null edits
1500 if ( $this->section != 'new' && !$this->allowBlankSummary
1501 && !$content->equals( $this->getOriginalContent() )
1502 && !$content->isRedirect() ) # check if it's not a redirect
1503 {
1504 if ( md5( $this->summary ) == $this->autoSumm ) {
1505 $this->missingSummary = true;
1506 $status->fatal( 'missingsummary' );
1507 $status->value = self::AS_SUMMARY_NEEDED;
1508 wfProfileOut( __METHOD__ );
1509 return $status;
1510 }
1511 }
1512
1513 # And a similar thing for new sections
1514 if ( $this->section == 'new' && !$this->allowBlankSummary ) {
1515 if ( trim( $this->summary ) == '' ) {
1516 $this->missingSummary = true;
1517 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
1518 $status->value = self::AS_SUMMARY_NEEDED;
1519 wfProfileOut( __METHOD__ );
1520 return $status;
1521 }
1522 }
1523
1524 # All's well
1525 wfProfileIn( __METHOD__ . '-sectionanchor' );
1526 $sectionanchor = '';
1527 if ( $this->section == 'new' ) {
1528 if ( $this->textbox1 == '' ) {
1529 $this->missingComment = true;
1530 $status->fatal( 'missingcommenttext' );
1531 $status->value = self::AS_TEXTBOX_EMPTY;
1532 wfProfileOut( __METHOD__ . '-sectionanchor' );
1533 wfProfileOut( __METHOD__ );
1534 return $status;
1535 }
1536 if ( $this->sectiontitle !== '' ) {
1537 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle );
1538 // If no edit summary was specified, create one automatically from the section
1539 // title and have it link to the new section. Otherwise, respect the summary as
1540 // passed.
1541 if ( $this->summary === '' ) {
1542 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle );
1543 $this->summary = wfMessage( 'newsectionsummary', $cleanSectionTitle )
1544 ->inContentLanguage()->text();
1545 }
1546 } elseif ( $this->summary !== '' ) {
1547 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->summary );
1548 # This is a new section, so create a link to the new section
1549 # in the revision summary.
1550 $cleanSummary = $wgParser->stripSectionName( $this->summary );
1551 $this->summary = wfMessage( 'newsectionsummary', $cleanSummary )
1552 ->inContentLanguage()->text();
1553 }
1554 } elseif ( $this->section != '' ) {
1555 # Try to get a section anchor from the section source, redirect to edited section if header found
1556 # XXX: might be better to integrate this into Article::replaceSection
1557 # for duplicate heading checking and maybe parsing
1558 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1, $matches );
1559 # we can't deal with anchors, includes, html etc in the header for now,
1560 # headline would need to be parsed to improve this
1561 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
1562 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $matches[2] );
1563 }
1564 }
1565 $result['sectionanchor'] = $sectionanchor;
1566 wfProfileOut( __METHOD__ . '-sectionanchor' );
1567
1568 // Save errors may fall down to the edit form, but we've now
1569 // merged the section into full text. Clear the section field
1570 // so that later submission of conflict forms won't try to
1571 // replace that into a duplicated mess.
1572 $this->textbox1 = $this->toEditText( $content );
1573 $this->section = '';
1574
1575 $status->value = self::AS_SUCCESS_UPDATE;
1576 }
1577
1578 // Check for length errors again now that the section is merged in
1579 $this->kblength = (int)( strlen( $this->toEditText( $content ) ) / 1024 );
1580 if ( $this->kblength > $wgMaxArticleSize ) {
1581 $this->tooBig = true;
1582 $status->setResult( false, self::AS_MAX_ARTICLE_SIZE_EXCEEDED );
1583 wfProfileOut( __METHOD__ );
1584 return $status;
1585 }
1586
1587 $flags = EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1588 ( $new ? EDIT_NEW : EDIT_UPDATE ) |
1589 ( ( $this->minoredit && !$this->isNew ) ? EDIT_MINOR : 0 ) |
1590 ( $bot ? EDIT_FORCE_BOT : 0 );
1591
1592 $doEditStatus = $this->mArticle->doEditContent( $content, $this->summary, $flags,
1593 false, null, $this->contentFormat );
1594
1595 if ( $doEditStatus->isOK() ) {
1596 $result['redirect'] = $content->isRedirect();
1597 $this->commitWatch();
1598 wfProfileOut( __METHOD__ );
1599 return $status;
1600 } else {
1601 // Failure from doEdit()
1602 // Show the edit conflict page for certain recognized errors from doEdit(),
1603 // but don't show it for errors from extension hooks
1604 $errors = $doEditStatus->getErrorsArray();
1605 if ( in_array( $errors[0][0], array( 'edit-gone-missing', 'edit-conflict',
1606 'edit-already-exists' ) ) )
1607 {
1608 $this->isConflict = true;
1609 // Destroys data doEdit() put in $status->value but who cares
1610 $doEditStatus->value = self::AS_END;
1611 }
1612 wfProfileOut( __METHOD__ );
1613 return $doEditStatus;
1614 }
1615 }
1616
1617 /**
1618 * Commit the change of watch status
1619 */
1620 protected function commitWatch() {
1621 global $wgUser;
1622 if ( $wgUser->isLoggedIn() && $this->watchthis != $wgUser->isWatched( $this->mTitle ) ) {
1623 $dbw = wfGetDB( DB_MASTER );
1624 $dbw->begin( __METHOD__ );
1625 if ( $this->watchthis ) {
1626 WatchAction::doWatch( $this->mTitle, $wgUser );
1627 } else {
1628 WatchAction::doUnwatch( $this->mTitle, $wgUser );
1629 }
1630 $dbw->commit( __METHOD__ );
1631 }
1632 }
1633
1634 /**
1635 * @private
1636 * @todo document
1637 *
1638 * @param $editText string
1639 *
1640 * @return bool
1641 * @deprecated since 1.21, use mergeChangesIntoContent() instead
1642 */
1643 function mergeChangesInto( &$editText ){
1644 wfDebug( __METHOD__, "1.21" );
1645
1646 $editContent = $this->toEditContent( $editText );
1647
1648 $ok = $this->mergeChangesIntoContent( $editContent );
1649
1650 if ( $ok ) {
1651 $editText = $this->toEditText( $editContent );
1652 return true;
1653 } else {
1654 return false;
1655 }
1656 }
1657
1658 /**
1659 * @private
1660 * @todo document
1661 *
1662 * @parma $editText string
1663 *
1664 * @return bool
1665 * @since since 1.WD
1666 */
1667 private function mergeChangesIntoContent( &$editContent ){
1668 wfProfileIn( __METHOD__ );
1669
1670 $db = wfGetDB( DB_MASTER );
1671
1672 // This is the revision the editor started from
1673 $baseRevision = $this->getBaseRevision();
1674 if ( is_null( $baseRevision ) ) {
1675 wfProfileOut( __METHOD__ );
1676 return false;
1677 }
1678 $baseContent = $baseRevision->getContent();
1679
1680 // The current state, we want to merge updates into it
1681 $currentRevision = Revision::loadFromTitle( $db, $this->mTitle );
1682 if ( is_null( $currentRevision ) ) {
1683 wfProfileOut( __METHOD__ );
1684 return false;
1685 }
1686 $currentContent = $currentRevision->getContent();
1687
1688 $handler = ContentHandler::getForModelID( $baseContent->getModel() );
1689
1690 $result = $handler->merge3( $baseContent, $editContent, $currentContent );
1691
1692 if ( $result ) {
1693 $editContent = $result;
1694 wfProfileOut( __METHOD__ );
1695 return true;
1696 } else {
1697 wfProfileOut( __METHOD__ );
1698 return false;
1699 }
1700 }
1701
1702 /**
1703 * @return Revision
1704 */
1705 function getBaseRevision() {
1706 if ( !$this->mBaseRevision ) {
1707 $db = wfGetDB( DB_MASTER );
1708 $baseRevision = Revision::loadFromTimestamp(
1709 $db, $this->mTitle, $this->edittime );
1710 return $this->mBaseRevision = $baseRevision;
1711 } else {
1712 return $this->mBaseRevision;
1713 }
1714 }
1715
1716 /**
1717 * Check given input text against $wgSpamRegex, and return the text of the first match.
1718 *
1719 * @param $text string
1720 *
1721 * @return string|bool matching string or false
1722 */
1723 public static function matchSpamRegex( $text ) {
1724 global $wgSpamRegex;
1725 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
1726 $regexes = (array)$wgSpamRegex;
1727 return self::matchSpamRegexInternal( $text, $regexes );
1728 }
1729
1730 /**
1731 * Check given input text against $wgSpamRegex, and return the text of the first match.
1732 *
1733 * @param $text string
1734 *
1735 * @return string|bool matching string or false
1736 */
1737 public static function matchSummarySpamRegex( $text ) {
1738 global $wgSummarySpamRegex;
1739 $regexes = (array)$wgSummarySpamRegex;
1740 return self::matchSpamRegexInternal( $text, $regexes );
1741 }
1742
1743 /**
1744 * @param $text string
1745 * @param $regexes array
1746 * @return bool|string
1747 */
1748 protected static function matchSpamRegexInternal( $text, $regexes ) {
1749 foreach ( $regexes as $regex ) {
1750 $matches = array();
1751 if ( preg_match( $regex, $text, $matches ) ) {
1752 return $matches[0];
1753 }
1754 }
1755 return false;
1756 }
1757
1758 function setHeaders() {
1759 global $wgOut, $wgUser;
1760
1761 $wgOut->addModules( 'mediawiki.action.edit' );
1762
1763 if ( $wgUser->getOption( 'uselivepreview', false ) ) {
1764 $wgOut->addModules( 'mediawiki.legacy.preview' );
1765 }
1766 // Bug #19334: textarea jumps when editing articles in IE8
1767 $wgOut->addStyle( 'common/IE80Fixes.css', 'screen', 'IE 8' );
1768
1769 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1770
1771 # Enabled article-related sidebar, toplinks, etc.
1772 $wgOut->setArticleRelated( true );
1773
1774 $contextTitle = $this->getContextTitle();
1775 if ( $this->isConflict ) {
1776 $msg = 'editconflict';
1777 } elseif ( $contextTitle->exists() && $this->section != '' ) {
1778 $msg = $this->section == 'new' ? 'editingcomment' : 'editingsection';
1779 } else {
1780 $msg = $contextTitle->exists() || ( $contextTitle->getNamespace() == NS_MEDIAWIKI && $contextTitle->getDefaultMessageText() !== false ) ?
1781 'editing' : 'creating';
1782 }
1783 # Use the title defined by DISPLAYTITLE magic word when present
1784 $displayTitle = isset( $this->mParserOutput ) ? $this->mParserOutput->getDisplayTitle() : false;
1785 if ( $displayTitle === false ) {
1786 $displayTitle = $contextTitle->getPrefixedText();
1787 }
1788 $wgOut->setPageTitle( wfMessage( $msg, $displayTitle ) );
1789 }
1790
1791 /**
1792 * Show all applicable editing introductions
1793 */
1794 protected function showIntro() {
1795 global $wgOut, $wgUser;
1796 if ( $this->suppressIntro ) {
1797 return;
1798 }
1799
1800 $namespace = $this->mTitle->getNamespace();
1801
1802 if ( $namespace == NS_MEDIAWIKI ) {
1803 # Show a warning if editing an interface message
1804 $wgOut->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
1805 } else if( $namespace == NS_FILE ) {
1806 # Show a hint to shared repo
1807 $file = wfFindFile( $this->mTitle );
1808 if( $file && !$file->isLocal() ) {
1809 $descUrl = $file->getDescriptionUrl();
1810 # there must be a description url to show a hint to shared repo
1811 if( $descUrl ) {
1812 if( !$this->mTitle->exists() ) {
1813 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", array (
1814 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
1815 ) );
1816 } else {
1817 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", array(
1818 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
1819 ) );
1820 }
1821 }
1822 }
1823 }
1824
1825 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
1826 # Show log extract when the user is currently blocked
1827 if ( $namespace == NS_USER || $namespace == NS_USER_TALK ) {
1828 $parts = explode( '/', $this->mTitle->getText(), 2 );
1829 $username = $parts[0];
1830 $user = User::newFromName( $username, false /* allow IP users*/ );
1831 $ip = User::isIP( $username );
1832 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
1833 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
1834 array( 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ) );
1835 } elseif ( $user->isBlocked() ) { # Show log extract if the user is currently blocked
1836 LogEventsList::showLogExtract(
1837 $wgOut,
1838 'block',
1839 $user->getUserPage(),
1840 '',
1841 array(
1842 'lim' => 1,
1843 'showIfEmpty' => false,
1844 'msgKey' => array(
1845 'blocked-notice-logextract',
1846 $user->getName() # Support GENDER in notice
1847 )
1848 )
1849 );
1850 }
1851 }
1852 # Try to add a custom edit intro, or use the standard one if this is not possible.
1853 if ( !$this->showCustomIntro() && !$this->mTitle->exists() ) {
1854 if ( $wgUser->isLoggedIn() ) {
1855 $wgOut->wrapWikiMsg( "<div class=\"mw-newarticletext\">\n$1\n</div>", 'newarticletext' );
1856 } else {
1857 $wgOut->wrapWikiMsg( "<div class=\"mw-newarticletextanon\">\n$1\n</div>", 'newarticletextanon' );
1858 }
1859 }
1860 # Give a notice if the user is editing a deleted/moved page...
1861 if ( !$this->mTitle->exists() ) {
1862 LogEventsList::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle,
1863 '', array( 'lim' => 10,
1864 'conds' => array( "log_action != 'revision'" ),
1865 'showIfEmpty' => false,
1866 'msgKey' => array( 'recreate-moveddeleted-warn' ) )
1867 );
1868 }
1869 }
1870
1871 /**
1872 * Attempt to show a custom editing introduction, if supplied
1873 *
1874 * @return bool
1875 */
1876 protected function showCustomIntro() {
1877 if ( $this->editintro ) {
1878 $title = Title::newFromText( $this->editintro );
1879 if ( $title instanceof Title && $title->exists() && $title->userCan( 'read' ) ) {
1880 global $wgOut;
1881 // Added using template syntax, to take <noinclude>'s into account.
1882 $wgOut->addWikiTextTitleTidy( '{{:' . $title->getFullText() . '}}', $this->mTitle );
1883 return true;
1884 } else {
1885 return false;
1886 }
1887 } else {
1888 return false;
1889 }
1890 }
1891
1892 /**
1893 * Gets an editable textual representation of the given Content object.
1894 * The textual representation can be turned by into a Content object by the
1895 * toEditContent() method.
1896 *
1897 * If the given Content object is not of a type that can be edited using the text base EditPage,
1898 * an exception will be raised. Set $this->allowNonTextContent to true to allow editing of non-textual
1899 * content.
1900 *
1901 * @param Content $content
1902 * @return String the editable text form of the content.
1903 *
1904 * @throws MWException if $content is not an instance of TextContent and $this->allowNonTextContent is not true.
1905 */
1906 protected function toEditText( Content $content ) {
1907 if ( !$this->allowNonTextContent && !( $content instanceof TextContent ) ) {
1908 throw new MWException( "This content model can not be edited as text: "
1909 . ContentHandler::getLocalizedName( $content->getModel() ) );
1910 }
1911
1912 return $content->serialize( $this->contentFormat );
1913 }
1914
1915 /**
1916 * Turns the given text into a Content object by unserializing it.
1917 *
1918 * If the resulting Content object is not of a type that can be edited using the text base EditPage,
1919 * an exception will be raised. Set $this->allowNonTextContent to true to allow editing of non-textual
1920 * content.
1921 *
1922 * @param String $text Text to unserialize
1923 * @return Content the content object created from $text
1924 *
1925 * @throws MWException if unserializing the text results in a Content object that is not an instance of TextContent
1926 * and $this->allowNonTextContent is not true.
1927 */
1928 protected function toEditContent( $text ) {
1929 $content = ContentHandler::makeContent( $text, $this->getTitle(),
1930 $this->contentModel, $this->contentFormat );
1931
1932 if ( !$this->allowNonTextContent && !( $content instanceof TextContent ) ) {
1933 throw new MWException( "This content model can not be edited as text: "
1934 . ContentHandler::getLocalizedName( $content->getModel() ) );
1935 }
1936
1937 return $content;
1938 }
1939
1940 /**
1941 * Send the edit form and related headers to $wgOut
1942 * @param $formCallback Callback that takes an OutputPage parameter; will be called
1943 * during form output near the top, for captchas and the like.
1944 */
1945 function showEditForm( $formCallback = null ) {
1946 global $wgOut, $wgUser;
1947
1948 wfProfileIn( __METHOD__ );
1949
1950 # need to parse the preview early so that we know which templates are used,
1951 # otherwise users with "show preview after edit box" will get a blank list
1952 # we parse this near the beginning so that setHeaders can do the title
1953 # setting work instead of leaving it in getPreviewText
1954 $previewOutput = '';
1955 if ( $this->formtype == 'preview' ) {
1956 $previewOutput = $this->getPreviewText();
1957 }
1958
1959 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this, &$wgOut ) );
1960
1961 $this->setHeaders();
1962
1963 if ( $this->showHeader() === false ) {
1964 wfProfileOut( __METHOD__ );
1965 return;
1966 }
1967
1968 $wgOut->addHTML( $this->editFormPageTop );
1969
1970 if ( $wgUser->getOption( 'previewontop' ) ) {
1971 $this->displayPreviewArea( $previewOutput, true );
1972 }
1973
1974 $wgOut->addHTML( $this->editFormTextTop );
1975
1976 $showToolbar = true;
1977 if ( $this->wasDeletedSinceLastEdit() ) {
1978 if ( $this->formtype == 'save' ) {
1979 // Hide the toolbar and edit area, user can click preview to get it back
1980 // Add an confirmation checkbox and explanation.
1981 $showToolbar = false;
1982 } else {
1983 $wgOut->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
1984 'deletedwhileediting' );
1985 }
1986 }
1987
1988 //@todo: add EditForm plugin interface and use it here!
1989 // search for textarea1 and textares2, and allow EditForm to override all uses.
1990 $wgOut->addHTML( Html::openElement( 'form', array( 'id' => self::EDITFORM_ID, 'name' => self::EDITFORM_ID,
1991 'method' => 'post', 'action' => $this->getActionURL( $this->getContextTitle() ),
1992 'enctype' => 'multipart/form-data' ) ) );
1993
1994 if ( is_callable( $formCallback ) ) {
1995 call_user_func_array( $formCallback, array( &$wgOut ) );
1996 }
1997
1998 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
1999
2000 // Put these up at the top to ensure they aren't lost on early form submission
2001 $this->showFormBeforeText();
2002
2003 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype ) {
2004 $username = $this->lastDelete->user_name;
2005 $comment = $this->lastDelete->log_comment;
2006
2007 // It is better to not parse the comment at all than to have templates expanded in the middle
2008 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
2009 $key = $comment === ''
2010 ? 'confirmrecreate-noreason'
2011 : 'confirmrecreate';
2012 $wgOut->addHTML(
2013 '<div class="mw-confirm-recreate">' .
2014 wfMessage( $key, $username, "<nowiki>$comment</nowiki>" )->parse() .
2015 Xml::checkLabel( wfMessage( 'recreate' )->text(), 'wpRecreate', 'wpRecreate', false,
2016 array( 'title' => Linker::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' )
2017 ) .
2018 '</div>'
2019 );
2020 }
2021
2022 # When the summary is hidden, also hide them on preview/show changes
2023 if( $this->nosummary ) {
2024 $wgOut->addHTML( Html::hidden( 'nosummary', true ) );
2025 }
2026
2027 # If a blank edit summary was previously provided, and the appropriate
2028 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
2029 # user being bounced back more than once in the event that a summary
2030 # is not required.
2031 #####
2032 # For a bit more sophisticated detection of blank summaries, hash the
2033 # automatic one and pass that in the hidden field wpAutoSummary.
2034 if ( $this->missingSummary || ( $this->section == 'new' && $this->nosummary ) ) {
2035 $wgOut->addHTML( Html::hidden( 'wpIgnoreBlankSummary', true ) );
2036 }
2037
2038 if ( $this->undidRev ) {
2039 $wgOut->addHTML( Html::hidden( 'wpUndidRevision', $this->undidRev ) );
2040 }
2041
2042 if ( $this->hasPresetSummary ) {
2043 // If a summary has been preset using &summary= we dont want to prompt for
2044 // a different summary. Only prompt for a summary if the summary is blanked.
2045 // (Bug 17416)
2046 $this->autoSumm = md5( '' );
2047 }
2048
2049 $autosumm = $this->autoSumm ? $this->autoSumm : md5( $this->summary );
2050 $wgOut->addHTML( Html::hidden( 'wpAutoSummary', $autosumm ) );
2051
2052 $wgOut->addHTML( Html::hidden( 'oldid', $this->oldid ) );
2053
2054 $wgOut->addHTML( Html::hidden( 'format', $this->contentFormat ) );
2055 $wgOut->addHTML( Html::hidden( 'model', $this->contentModel ) );
2056
2057 if ( $this->section == 'new' ) {
2058 $this->showSummaryInput( true, $this->summary );
2059 $wgOut->addHTML( $this->getSummaryPreview( true, $this->summary ) );
2060 }
2061
2062 $wgOut->addHTML( $this->editFormTextBeforeContent );
2063
2064 if ( !$this->isCssJsSubpage && $showToolbar && $wgUser->getOption( 'showtoolbar' ) ) {
2065 $wgOut->addHTML( EditPage::getEditToolbar() );
2066 }
2067
2068 if ( $this->isConflict ) {
2069 // In an edit conflict bypass the overrideable content form method
2070 // and fallback to the raw wpTextbox1 since editconflicts can't be
2071 // resolved between page source edits and custom ui edits using the
2072 // custom edit ui.
2073 $this->textbox2 = $this->textbox1;
2074
2075 $content = $this->getCurrentContent();
2076 $this->textbox1 = $this->toEditText( $content );
2077
2078 $this->showTextbox1();
2079 } else {
2080 $this->showContentForm();
2081 }
2082
2083 $wgOut->addHTML( $this->editFormTextAfterContent );
2084
2085 $this->showStandardInputs();
2086
2087 $this->showFormAfterText();
2088
2089 $this->showTosSummary();
2090
2091 $this->showEditTools();
2092
2093 $wgOut->addHTML( $this->editFormTextAfterTools . "\n" );
2094
2095 $wgOut->addHTML( Html::rawElement( 'div', array( 'class' => 'templatesUsed' ),
2096 Linker::formatTemplates( $this->getTemplates(), $this->preview, $this->section != '' ) ) );
2097
2098 $wgOut->addHTML( Html::rawElement( 'div', array( 'class' => 'hiddencats' ),
2099 Linker::formatHiddenCategories( $this->mArticle->getHiddenCategories() ) ) );
2100
2101 if ( $this->isConflict ) {
2102 try {
2103 $this->showConflict();
2104 } catch ( MWContentSerializationException $ex ) {
2105 // this can't really happen, but be nice if it does.
2106 $msg = wfMessage( 'content-failed-to-parse', $this->contentModel, $this->contentFormat, $ex->getMessage() );
2107 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>');
2108 }
2109 }
2110
2111 $wgOut->addHTML( $this->editFormTextBottom . "\n</form>\n" );
2112
2113 if ( !$wgUser->getOption( 'previewontop' ) ) {
2114 $this->displayPreviewArea( $previewOutput, false );
2115 }
2116
2117 wfProfileOut( __METHOD__ );
2118 }
2119
2120 /**
2121 * Extract the section title from current section text, if any.
2122 *
2123 * @param string $text
2124 * @return Mixed|string or false
2125 */
2126 public static function extractSectionTitle( $text ) {
2127 preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
2128 if ( !empty( $matches[2] ) ) {
2129 global $wgParser;
2130 return $wgParser->stripSectionName( trim( $matches[2] ) );
2131 } else {
2132 return false;
2133 }
2134 }
2135
2136 protected function showHeader() {
2137 global $wgOut, $wgUser, $wgMaxArticleSize, $wgLang;
2138
2139 if ( $this->mTitle->isTalkPage() ) {
2140 $wgOut->addWikiMsg( 'talkpagetext' );
2141 }
2142
2143 # Optional notices on a per-namespace and per-page basis
2144 $editnotice_ns = 'editnotice-' . $this->mTitle->getNamespace();
2145 $editnotice_ns_message = wfMessage( $editnotice_ns );
2146 if ( $editnotice_ns_message->exists() ) {
2147 $wgOut->addWikiText( $editnotice_ns_message->plain() );
2148 }
2149 if ( MWNamespace::hasSubpages( $this->mTitle->getNamespace() ) ) {
2150 $parts = explode( '/', $this->mTitle->getDBkey() );
2151 $editnotice_base = $editnotice_ns;
2152 while ( count( $parts ) > 0 ) {
2153 $editnotice_base .= '-' . array_shift( $parts );
2154 $editnotice_base_msg = wfMessage( $editnotice_base );
2155 if ( $editnotice_base_msg->exists() ) {
2156 $wgOut->addWikiText( $editnotice_base_msg->plain() );
2157 }
2158 }
2159 } else {
2160 # Even if there are no subpages in namespace, we still don't want / in MW ns.
2161 $editnoticeText = $editnotice_ns . '-' . str_replace( '/', '-', $this->mTitle->getDBkey() );
2162 $editnoticeMsg = wfMessage( $editnoticeText );
2163 if ( $editnoticeMsg->exists() ) {
2164 $wgOut->addWikiText( $editnoticeMsg->plain() );
2165 }
2166 }
2167
2168 if ( $this->isConflict ) {
2169 $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1\n</div>", 'explainconflict' );
2170 $this->edittime = $this->mArticle->getTimestamp();
2171 } else {
2172 if ( $this->section != '' && !$this->isSectionEditSupported() ) {
2173 // We use $this->section to much before this and getVal('wgSection') directly in other places
2174 // at this point we can't reset $this->section to '' to fallback to non-section editing.
2175 // Someone is welcome to try refactoring though
2176 $wgOut->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2177 return false;
2178 }
2179
2180 if ( $this->section != '' && $this->section != 'new' ) {
2181 if ( !$this->summary && !$this->preview && !$this->diff ) {
2182 $sectionTitle = self::extractSectionTitle( $this->textbox1 ); //FIXME: use Content object
2183 if ( $sectionTitle !== false ) {
2184 $this->summary = "/* $sectionTitle */ ";
2185 }
2186 }
2187 }
2188
2189 if ( $this->missingComment ) {
2190 $wgOut->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
2191 }
2192
2193 if ( $this->missingSummary && $this->section != 'new' ) {
2194 $wgOut->wrapWikiMsg( "<div id='mw-missingsummary'>\n$1\n</div>", 'missingsummary' );
2195 }
2196
2197 if ( $this->missingSummary && $this->section == 'new' ) {
2198 $wgOut->wrapWikiMsg( "<div id='mw-missingcommentheader'>\n$1\n</div>", 'missingcommentheader' );
2199 }
2200
2201 if ( $this->hookError !== '' ) {
2202 $wgOut->addWikiText( $this->hookError );
2203 }
2204
2205 if ( !$this->checkUnicodeCompliantBrowser() ) {
2206 $wgOut->addWikiMsg( 'nonunicodebrowser' );
2207 }
2208
2209 if ( $this->section != 'new' ) {
2210 $revision = $this->mArticle->getRevisionFetched();
2211 if ( $revision ) {
2212 // Let sysop know that this will make private content public if saved
2213
2214 if ( !$revision->userCan( Revision::DELETED_TEXT ) ) {
2215 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-permission' );
2216 } elseif ( $revision->isDeleted( Revision::DELETED_TEXT ) ) {
2217 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-view' );
2218 }
2219
2220 if ( !$revision->isCurrent() ) {
2221 $this->mArticle->setOldSubtitle( $revision->getId() );
2222 $wgOut->addWikiMsg( 'editingold' );
2223 }
2224 } elseif ( $this->mTitle->exists() ) {
2225 // Something went wrong
2226
2227 $wgOut->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
2228 array( 'missing-revision', $this->oldid ) );
2229 }
2230 }
2231 }
2232
2233 if ( wfReadOnly() ) {
2234 $wgOut->wrapWikiMsg( "<div id=\"mw-read-only-warning\">\n$1\n</div>", array( 'readonlywarning', wfReadOnlyReason() ) );
2235 } elseif ( $wgUser->isAnon() ) {
2236 if ( $this->formtype != 'preview' ) {
2237 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-edit-warning\">\n$1</div>", 'anoneditwarning' );
2238 } else {
2239 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\">\n$1</div>", 'anonpreviewwarning' );
2240 }
2241 } else {
2242 if ( $this->isCssJsSubpage ) {
2243 # Check the skin exists
2244 if ( $this->isWrongCaseCssJsPage ) {
2245 $wgOut->wrapWikiMsg( "<div class='error' id='mw-userinvalidcssjstitle'>\n$1\n</div>", array( 'userinvalidcssjstitle', $this->mTitle->getSkinFromCssJsSubpage() ) );
2246 }
2247 if ( $this->formtype !== 'preview' ) {
2248 if ( $this->isCssSubpage )
2249 $wgOut->wrapWikiMsg( "<div id='mw-usercssyoucanpreview'>\n$1\n</div>", array( 'usercssyoucanpreview' ) );
2250 if ( $this->isJsSubpage )
2251 $wgOut->wrapWikiMsg( "<div id='mw-userjsyoucanpreview'>\n$1\n</div>", array( 'userjsyoucanpreview' ) );
2252 }
2253 }
2254 }
2255
2256 if ( $this->mTitle->getNamespace() != NS_MEDIAWIKI && $this->mTitle->isProtected( 'edit' ) ) {
2257 # Is the title semi-protected?
2258 if ( $this->mTitle->isSemiProtected() ) {
2259 $noticeMsg = 'semiprotectedpagewarning';
2260 } else {
2261 # Then it must be protected based on static groups (regular)
2262 $noticeMsg = 'protectedpagewarning';
2263 }
2264 LogEventsList::showLogExtract( $wgOut, 'protect', $this->mTitle, '',
2265 array( 'lim' => 1, 'msgKey' => array( $noticeMsg ) ) );
2266 }
2267 if ( $this->mTitle->isCascadeProtected() ) {
2268 # Is this page under cascading protection from some source pages?
2269 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle->getCascadeProtectionSources();
2270 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
2271 $cascadeSourcesCount = count( $cascadeSources );
2272 if ( $cascadeSourcesCount > 0 ) {
2273 # Explain, and list the titles responsible
2274 foreach ( $cascadeSources as $page ) {
2275 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
2276 }
2277 }
2278 $notice .= '</div>';
2279 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', $cascadeSourcesCount ) );
2280 }
2281 if ( !$this->mTitle->exists() && $this->mTitle->getRestrictions( 'create' ) ) {
2282 LogEventsList::showLogExtract( $wgOut, 'protect', $this->mTitle, '',
2283 array( 'lim' => 1,
2284 'showIfEmpty' => false,
2285 'msgKey' => array( 'titleprotectedwarning' ),
2286 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ) );
2287 }
2288
2289 if ( $this->kblength === false ) {
2290 $this->kblength = (int)( strlen( $this->textbox1 ) / 1024 );
2291 }
2292
2293 if ( $this->tooBig || $this->kblength > $wgMaxArticleSize ) {
2294 $wgOut->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
2295 array( 'longpageerror', $wgLang->formatNum( $this->kblength ), $wgLang->formatNum( $wgMaxArticleSize ) ) );
2296 } else {
2297 if ( !wfMessage( 'longpage-hint' )->isDisabled() ) {
2298 $wgOut->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
2299 array( 'longpage-hint', $wgLang->formatSize( strlen( $this->textbox1 ) ), strlen( $this->textbox1 ) )
2300 );
2301 }
2302 }
2303 # Add header copyright warning
2304 $this->showHeaderCopyrightWarning();
2305 }
2306
2307
2308 /**
2309 * Standard summary input and label (wgSummary), abstracted so EditPage
2310 * subclasses may reorganize the form.
2311 * Note that you do not need to worry about the label's for=, it will be
2312 * inferred by the id given to the input. You can remove them both by
2313 * passing array( 'id' => false ) to $userInputAttrs.
2314 *
2315 * @param $summary string The value of the summary input
2316 * @param $labelText string The html to place inside the label
2317 * @param $inputAttrs array of attrs to use on the input
2318 * @param $spanLabelAttrs array of attrs to use on the span inside the label
2319 *
2320 * @return array An array in the format array( $label, $input )
2321 */
2322 function getSummaryInput( $summary = "", $labelText = null, $inputAttrs = null, $spanLabelAttrs = null ) {
2323 // Note: the maxlength is overriden in JS to 255 and to make it use UTF-8 bytes, not characters.
2324 $inputAttrs = ( is_array( $inputAttrs ) ? $inputAttrs : array() ) + array(
2325 'id' => 'wpSummary',
2326 'maxlength' => '200',
2327 'tabindex' => '1',
2328 'size' => 60,
2329 'spellcheck' => 'true',
2330 ) + Linker::tooltipAndAccesskeyAttribs( 'summary' );
2331
2332 $spanLabelAttrs = ( is_array( $spanLabelAttrs ) ? $spanLabelAttrs : array() ) + array(
2333 'class' => $this->missingSummary ? 'mw-summarymissed' : 'mw-summary',
2334 'id' => "wpSummaryLabel"
2335 );
2336
2337 $label = null;
2338 if ( $labelText ) {
2339 $label = Xml::tags( 'label', $inputAttrs['id'] ? array( 'for' => $inputAttrs['id'] ) : null, $labelText );
2340 $label = Xml::tags( 'span', $spanLabelAttrs, $label );
2341 }
2342
2343 $input = Html::input( 'wpSummary', $summary, 'text', $inputAttrs );
2344
2345 return array( $label, $input );
2346 }
2347
2348 /**
2349 * @param $isSubjectPreview Boolean: true if this is the section subject/title
2350 * up top, or false if this is the comment summary
2351 * down below the textarea
2352 * @param $summary String: The text of the summary to display
2353 * @return String
2354 */
2355 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
2356 global $wgOut, $wgContLang;
2357 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
2358 $summaryClass = $this->missingSummary ? 'mw-summarymissed' : 'mw-summary';
2359 if ( $isSubjectPreview ) {
2360 if ( $this->nosummary ) {
2361 return;
2362 }
2363 } else {
2364 if ( !$this->mShowSummaryField ) {
2365 return;
2366 }
2367 }
2368 $summary = $wgContLang->recodeForEdit( $summary );
2369 $labelText = wfMessage( $isSubjectPreview ? 'subject' : 'summary' )->parse();
2370 list( $label, $input ) = $this->getSummaryInput( $summary, $labelText, array( 'class' => $summaryClass ), array() );
2371 $wgOut->addHTML( "{$label} {$input}" );
2372 }
2373
2374 /**
2375 * @param $isSubjectPreview Boolean: true if this is the section subject/title
2376 * up top, or false if this is the comment summary
2377 * down below the textarea
2378 * @param $summary String: the text of the summary to display
2379 * @return String
2380 */
2381 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
2382 if ( !$summary || ( !$this->preview && !$this->diff ) )
2383 return "";
2384
2385 global $wgParser;
2386
2387 if ( $isSubjectPreview )
2388 $summary = wfMessage( 'newsectionsummary', $wgParser->stripSectionName( $summary ) )
2389 ->inContentLanguage()->text();
2390
2391 $message = $isSubjectPreview ? 'subject-preview' : 'summary-preview';
2392
2393 $summary = wfMessage( $message )->parse() . Linker::commentBlock( $summary, $this->mTitle, $isSubjectPreview );
2394 return Xml::tags( 'div', array( 'class' => 'mw-summary-preview' ), $summary );
2395 }
2396
2397 protected function showFormBeforeText() {
2398 global $wgOut;
2399 $section = htmlspecialchars( $this->section );
2400 $wgOut->addHTML( <<<HTML
2401 <input type='hidden' value="{$section}" name="wpSection" />
2402 <input type='hidden' value="{$this->starttime}" name="wpStarttime" />
2403 <input type='hidden' value="{$this->edittime}" name="wpEdittime" />
2404 <input type='hidden' value="{$this->scrolltop}" name="wpScrolltop" id="wpScrolltop" />
2405
2406 HTML
2407 );
2408 if ( !$this->checkUnicodeCompliantBrowser() )
2409 $wgOut->addHTML( Html::hidden( 'safemode', '1' ) );
2410 }
2411
2412 protected function showFormAfterText() {
2413 global $wgOut, $wgUser;
2414 /**
2415 * To make it harder for someone to slip a user a page
2416 * which submits an edit form to the wiki without their
2417 * knowledge, a random token is associated with the login
2418 * session. If it's not passed back with the submission,
2419 * we won't save the page, or render user JavaScript and
2420 * CSS previews.
2421 *
2422 * For anon editors, who may not have a session, we just
2423 * include the constant suffix to prevent editing from
2424 * broken text-mangling proxies.
2425 */
2426 $wgOut->addHTML( "\n" . Html::hidden( "wpEditToken", $wgUser->getEditToken() ) . "\n" );
2427 }
2428
2429 /**
2430 * Subpage overridable method for printing the form for page content editing
2431 * By default this simply outputs wpTextbox1
2432 * Subclasses can override this to provide a custom UI for editing;
2433 * be it a form, or simply wpTextbox1 with a modified content that will be
2434 * reverse modified when extracted from the post data.
2435 * Note that this is basically the inverse for importContentFormData
2436 */
2437 protected function showContentForm() {
2438 $this->showTextbox1();
2439 }
2440
2441 /**
2442 * Method to output wpTextbox1
2443 * The $textoverride method can be used by subclasses overriding showContentForm
2444 * to pass back to this method.
2445 *
2446 * @param $customAttribs array of html attributes to use in the textarea
2447 * @param $textoverride String: optional text to override $this->textarea1 with
2448 */
2449 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
2450 if ( $this->wasDeletedSinceLastEdit() && $this->formtype == 'save' ) {
2451 $attribs = array( 'style' => 'display:none;' );
2452 } else {
2453 $classes = array(); // Textarea CSS
2454 if ( $this->mTitle->getNamespace() != NS_MEDIAWIKI && $this->mTitle->isProtected( 'edit' ) ) {
2455 # Is the title semi-protected?
2456 if ( $this->mTitle->isSemiProtected() ) {
2457 $classes[] = 'mw-textarea-sprotected';
2458 } else {
2459 # Then it must be protected based on static groups (regular)
2460 $classes[] = 'mw-textarea-protected';
2461 }
2462 # Is the title cascade-protected?
2463 if ( $this->mTitle->isCascadeProtected() ) {
2464 $classes[] = 'mw-textarea-cprotected';
2465 }
2466 }
2467
2468 $attribs = array( 'tabindex' => 1 );
2469
2470 if ( is_array( $customAttribs ) ) {
2471 $attribs += $customAttribs;
2472 }
2473
2474 if ( count( $classes ) ) {
2475 if ( isset( $attribs['class'] ) ) {
2476 $classes[] = $attribs['class'];
2477 }
2478 $attribs['class'] = implode( ' ', $classes );
2479 }
2480 }
2481
2482 $this->showTextbox( $textoverride !== null ? $textoverride : $this->textbox1, 'wpTextbox1', $attribs );
2483 }
2484
2485 protected function showTextbox2() {
2486 $this->showTextbox( $this->textbox2, 'wpTextbox2', array( 'tabindex' => 6, 'readonly' ) );
2487 }
2488
2489 protected function showTextbox( $text, $name, $customAttribs = array() ) {
2490 global $wgOut, $wgUser;
2491
2492 $wikitext = $this->safeUnicodeOutput( $text );
2493 if ( strval( $wikitext ) !== '' ) {
2494 // Ensure there's a newline at the end, otherwise adding lines
2495 // is awkward.
2496 // But don't add a newline if the ext is empty, or Firefox in XHTML
2497 // mode will show an extra newline. A bit annoying.
2498 $wikitext .= "\n";
2499 }
2500
2501 $attribs = $customAttribs + array(
2502 'accesskey' => ',',
2503 'id' => $name,
2504 'cols' => $wgUser->getIntOption( 'cols' ),
2505 'rows' => $wgUser->getIntOption( 'rows' ),
2506 'style' => '' // avoid php notices when appending preferences (appending allows customAttribs['style'] to still work
2507 );
2508
2509 $pageLang = $this->mTitle->getPageLanguage();
2510 $attribs['lang'] = $pageLang->getCode();
2511 $attribs['dir'] = $pageLang->getDir();
2512
2513 $wgOut->addHTML( Html::textarea( $name, $wikitext, $attribs ) );
2514 }
2515
2516 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
2517 global $wgOut;
2518 $classes = array();
2519 if ( $isOnTop )
2520 $classes[] = 'ontop';
2521
2522 $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) );
2523
2524 if ( $this->formtype != 'preview' )
2525 $attribs['style'] = 'display: none;';
2526
2527 $wgOut->addHTML( Xml::openElement( 'div', $attribs ) );
2528
2529 if ( $this->formtype == 'preview' ) {
2530 $this->showPreview( $previewOutput );
2531 }
2532
2533 $wgOut->addHTML( '</div>' );
2534
2535 if ( $this->formtype == 'diff' ) {
2536 try {
2537 $this->showDiff();
2538 } catch ( MWContentSerializationException $ex ) {
2539 $msg = wfMessage( 'content-failed-to-parse', $this->contentModel, $this->contentFormat, $ex->getMessage() );
2540 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>');
2541 }
2542 }
2543 }
2544
2545 /**
2546 * Append preview output to $wgOut.
2547 * Includes category rendering if this is a category page.
2548 *
2549 * @param $text String: the HTML to be output for the preview.
2550 */
2551 protected function showPreview( $text ) {
2552 global $wgOut;
2553 if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
2554 $this->mArticle->openShowCategory();
2555 }
2556 # This hook seems slightly odd here, but makes things more
2557 # consistent for extensions.
2558 wfRunHooks( 'OutputPageBeforeHTML', array( &$wgOut, &$text ) );
2559 $wgOut->addHTML( $text );
2560 if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
2561 $this->mArticle->closeShowCategory();
2562 }
2563 }
2564
2565 /**
2566 * Get a diff between the current contents of the edit box and the
2567 * version of the page we're editing from.
2568 *
2569 * If this is a section edit, we'll replace the section as for final
2570 * save and then make a comparison.
2571 */
2572 function showDiff() {
2573 global $wgUser, $wgContLang, $wgParser, $wgOut;
2574
2575 $oldtitlemsg = 'currentrev';
2576 # if message does not exist, show diff against the preloaded default
2577 if( $this->mTitle->getNamespace() == NS_MEDIAWIKI && !$this->mTitle->exists() ) {
2578 $oldtext = $this->mTitle->getDefaultMessageText();
2579 if( $oldtext !== false ) {
2580 $oldtitlemsg = 'defaultmessagetext';
2581 $oldContent = $this->toEditContent( $oldtext );
2582 } else {
2583 $oldContent = null;
2584 }
2585 } else {
2586 $oldContent = $this->getOriginalContent();
2587 }
2588
2589 $textboxContent = $this->toEditContent( $this->textbox1 );
2590
2591 $newContent = $this->mArticle->replaceSectionContent(
2592 $this->section, $textboxContent,
2593 $this->summary, $this->edittime );
2594
2595 ContentHandler::runLegacyHooks( 'EditPageGetDiffText', array( $this, &$newContent ) );
2596 wfRunHooks( 'EditPageGetDiffContent', array( $this, &$newContent ) );
2597
2598 $popts = ParserOptions::newFromUserAndLang( $wgUser, $wgContLang );
2599 $newContent = $newContent->preSaveTransform( $this->mTitle, $wgUser, $popts );
2600
2601 if ( ( $oldContent && !$oldContent->isEmpty() ) || ( $newContent && !$newContent->isEmpty() ) ) {
2602 $oldtitle = wfMessage( $oldtitlemsg )->parse();
2603 $newtitle = wfMessage( 'yourtext' )->parse();
2604
2605 $de = $oldContent->getContentHandler()->createDifferenceEngine( $this->mArticle->getContext() );
2606 $de->setContent( $oldContent, $newContent );
2607
2608 $difftext = $de->getDiff( $oldtitle, $newtitle );
2609 $de->showDiffStyle();
2610 } else {
2611 $difftext = '';
2612 }
2613
2614 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
2615 }
2616
2617 /**
2618 * Show the header copyright warning.
2619 */
2620 protected function showHeaderCopyrightWarning() {
2621 $msg = 'editpage-head-copy-warn';
2622 if ( !wfMessage( $msg )->isDisabled() ) {
2623 global $wgOut;
2624 $wgOut->wrapWikiMsg( "<div class='editpage-head-copywarn'>\n$1\n</div>",
2625 'editpage-head-copy-warn' );
2626 }
2627 }
2628
2629 /**
2630 * Give a chance for site and per-namespace customizations of
2631 * terms of service summary link that might exist separately
2632 * from the copyright notice.
2633 *
2634 * This will display between the save button and the edit tools,
2635 * so should remain short!
2636 */
2637 protected function showTosSummary() {
2638 $msg = 'editpage-tos-summary';
2639 wfRunHooks( 'EditPageTosSummary', array( $this->mTitle, &$msg ) );
2640 if ( !wfMessage( $msg )->isDisabled() ) {
2641 global $wgOut;
2642 $wgOut->addHTML( '<div class="mw-tos-summary">' );
2643 $wgOut->addWikiMsg( $msg );
2644 $wgOut->addHTML( '</div>' );
2645 }
2646 }
2647
2648 protected function showEditTools() {
2649 global $wgOut;
2650 $wgOut->addHTML( '<div class="mw-editTools">' .
2651 wfMessage( 'edittools' )->inContentLanguage()->parse() .
2652 '</div>' );
2653 }
2654
2655 /**
2656 * Get the copyright warning
2657 *
2658 * Renamed to getCopyrightWarning(), old name kept around for backwards compatibility
2659 */
2660 protected function getCopywarn() {
2661 return self::getCopyrightWarning( $this->mTitle );
2662 }
2663
2664 public static function getCopyrightWarning( $title ) {
2665 global $wgRightsText;
2666 if ( $wgRightsText ) {
2667 $copywarnMsg = array( 'copyrightwarning',
2668 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]',
2669 $wgRightsText );
2670 } else {
2671 $copywarnMsg = array( 'copyrightwarning2',
2672 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]' );
2673 }
2674 // Allow for site and per-namespace customization of contribution/copyright notice.
2675 wfRunHooks( 'EditPageCopyrightWarning', array( $title, &$copywarnMsg ) );
2676
2677 return "<div id=\"editpage-copywarn\">\n" .
2678 call_user_func_array( 'wfMessage', $copywarnMsg )->plain() . "\n</div>";
2679 }
2680
2681 protected function showStandardInputs( &$tabindex = 2 ) {
2682 global $wgOut;
2683 $wgOut->addHTML( "<div class='editOptions'>\n" );
2684
2685 if ( $this->section != 'new' ) {
2686 $this->showSummaryInput( false, $this->summary );
2687 $wgOut->addHTML( $this->getSummaryPreview( false, $this->summary ) );
2688 }
2689
2690 $checkboxes = $this->getCheckboxes( $tabindex,
2691 array( 'minor' => $this->minoredit, 'watch' => $this->watchthis ) );
2692 $wgOut->addHTML( "<div class='editCheckboxes'>" . implode( $checkboxes, "\n" ) . "</div>\n" );
2693
2694 // Show copyright warning.
2695 $wgOut->addWikiText( $this->getCopywarn() );
2696 $wgOut->addHTML( $this->editFormTextAfterWarn );
2697
2698 $wgOut->addHTML( "<div class='editButtons'>\n" );
2699 $wgOut->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
2700
2701 $cancel = $this->getCancelLink();
2702 if ( $cancel !== '' ) {
2703 $cancel .= wfMessage( 'pipe-separator' )->text();
2704 }
2705 $edithelpurl = Skin::makeInternalOrExternalUrl( wfMessage( 'edithelppage' )->inContentLanguage()->text() );
2706 $edithelp = '<a target="helpwindow" href="' . $edithelpurl . '">' .
2707 wfMessage( 'edithelp' )->escaped() . '</a> ' .
2708 wfMessage( 'newwindow' )->parse();
2709 $wgOut->addHTML( " <span class='cancelLink'>{$cancel}</span>\n" );
2710 $wgOut->addHTML( " <span class='editHelp'>{$edithelp}</span>\n" );
2711 $wgOut->addHTML( "</div><!-- editButtons -->\n</div><!-- editOptions -->\n" );
2712 }
2713
2714 /**
2715 * Show an edit conflict. textbox1 is already shown in showEditForm().
2716 * If you want to use another entry point to this function, be careful.
2717 */
2718 protected function showConflict() {
2719 global $wgOut;
2720
2721 if ( wfRunHooks( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
2722 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
2723
2724 $content1 = $this->toEditContent( $this->textbox1 );
2725 $content2 = $this->toEditContent( $this->textbox2 );
2726
2727 $handler = ContentHandler::getForModelID( $this->contentModel );
2728 $de = $handler->createDifferenceEngine( $this->mArticle->getContext() );
2729 $de->setContent( $content2, $content1 );
2730 $de->showDiff(
2731 wfMessage( 'yourtext' )->parse(),
2732 wfMessage( 'storedversion' )->text()
2733 );
2734
2735 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
2736 $this->showTextbox2();
2737 }
2738 }
2739
2740 /**
2741 * @return string
2742 */
2743 public function getCancelLink() {
2744 $cancelParams = array();
2745 if ( !$this->isConflict && $this->oldid > 0 ) {
2746 $cancelParams['oldid'] = $this->oldid;
2747 }
2748
2749 return Linker::linkKnown(
2750 $this->getContextTitle(),
2751 wfMessage( 'cancel' )->parse(),
2752 array( 'id' => 'mw-editform-cancel' ),
2753 $cancelParams
2754 );
2755 }
2756
2757 /**
2758 * Returns the URL to use in the form's action attribute.
2759 * This is used by EditPage subclasses when simply customizing the action
2760 * variable in the constructor is not enough. This can be used when the
2761 * EditPage lives inside of a Special page rather than a custom page action.
2762 *
2763 * @param $title Title object for which is being edited (where we go to for &action= links)
2764 * @return string
2765 */
2766 protected function getActionURL( Title $title ) {
2767 return $title->getLocalURL( array( 'action' => $this->action ) );
2768 }
2769
2770 /**
2771 * Check if a page was deleted while the user was editing it, before submit.
2772 * Note that we rely on the logging table, which hasn't been always there,
2773 * but that doesn't matter, because this only applies to brand new
2774 * deletes.
2775 */
2776 protected function wasDeletedSinceLastEdit() {
2777 if ( $this->deletedSinceEdit !== null ) {
2778 return $this->deletedSinceEdit;
2779 }
2780
2781 $this->deletedSinceEdit = false;
2782
2783 if ( $this->mTitle->isDeletedQuick() ) {
2784 $this->lastDelete = $this->getLastDelete();
2785 if ( $this->lastDelete ) {
2786 $deleteTime = wfTimestamp( TS_MW, $this->lastDelete->log_timestamp );
2787 if ( $deleteTime > $this->starttime ) {
2788 $this->deletedSinceEdit = true;
2789 }
2790 }
2791 }
2792
2793 return $this->deletedSinceEdit;
2794 }
2795
2796 protected function getLastDelete() {
2797 $dbr = wfGetDB( DB_SLAVE );
2798 $data = $dbr->selectRow(
2799 array( 'logging', 'user' ),
2800 array( 'log_type',
2801 'log_action',
2802 'log_timestamp',
2803 'log_user',
2804 'log_namespace',
2805 'log_title',
2806 'log_comment',
2807 'log_params',
2808 'log_deleted',
2809 'user_name' ),
2810 array( 'log_namespace' => $this->mTitle->getNamespace(),
2811 'log_title' => $this->mTitle->getDBkey(),
2812 'log_type' => 'delete',
2813 'log_action' => 'delete',
2814 'user_id=log_user' ),
2815 __METHOD__,
2816 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
2817 );
2818 // Quick paranoid permission checks...
2819 if ( is_object( $data ) ) {
2820 if ( $data->log_deleted & LogPage::DELETED_USER )
2821 $data->user_name = wfMessage( 'rev-deleted-user' )->escaped();
2822 if ( $data->log_deleted & LogPage::DELETED_COMMENT )
2823 $data->log_comment = wfMessage( 'rev-deleted-comment' )->escaped();
2824 }
2825 return $data;
2826 }
2827
2828 /**
2829 * Get the rendered text for previewing.
2830 * @return string
2831 */
2832 function getPreviewText() {
2833 global $wgOut, $wgUser, $wgParser, $wgRawHtml, $wgLang;
2834
2835 wfProfileIn( __METHOD__ );
2836
2837 if ( $wgRawHtml && !$this->mTokenOk ) {
2838 // Could be an offsite preview attempt. This is very unsafe if
2839 // HTML is enabled, as it could be an attack.
2840 $parsedNote = '';
2841 if ( $this->textbox1 !== '' ) {
2842 // Do not put big scary notice, if previewing the empty
2843 // string, which happens when you initially edit
2844 // a category page, due to automatic preview-on-open.
2845 $parsedNote = $wgOut->parse( "<div class='previewnote'>" .
2846 wfMessage( 'session_fail_preview_html' )->text() . "</div>", true, /* interface */true );
2847 }
2848 wfProfileOut( __METHOD__ );
2849 return $parsedNote;
2850 }
2851
2852 $note = '';
2853
2854 try {
2855 $content = $this->toEditContent( $this->textbox1 );
2856
2857 if ( $this->mTriedSave && !$this->mTokenOk ) {
2858 if ( $this->mTokenOkExceptSuffix ) {
2859 $note = wfMessage( 'token_suffix_mismatch' )->plain() ;
2860
2861 } else {
2862 $note = wfMessage( 'session_fail_preview' )->plain() ;
2863 }
2864 } elseif ( $this->incompleteForm ) {
2865 $note = wfMessage( 'edit_form_incomplete' )->plain() ;
2866 } else {
2867 $note = wfMessage( 'previewnote' )->plain() .
2868 ' [[#' . self::EDITFORM_ID . '|' . $wgLang->getArrow() . ' ' . wfMessage( 'continue-editing' )->text() . ']]';
2869 }
2870
2871 $parserOptions = $this->mArticle->makeParserOptions( $this->mArticle->getContext() );
2872 $parserOptions->setEditSection( false );
2873 $parserOptions->setIsPreview( true );
2874 $parserOptions->setIsSectionPreview( !is_null($this->section) && $this->section !== '' );
2875
2876 # don't parse non-wikitext pages, show message about preview
2877 if ( $this->mTitle->isCssJsSubpage() || $this->mTitle->isCssOrJsPage() ) {
2878 if( $this->mTitle->isCssJsSubpage() ) {
2879 $level = 'user';
2880 } elseif( $this->mTitle->isCssOrJsPage() ) {
2881 $level = 'site';
2882 } else {
2883 $level = false;
2884 }
2885
2886 if ( $content->getModel() == CONTENT_MODEL_CSS ) {
2887 $format = 'css';
2888 } elseif ( $content->getModel() == CONTENT_MODEL_JAVASCRIPT ) {
2889 $format = 'js';
2890 } else {
2891 $format = false;
2892 }
2893
2894 # Used messages to make sure grep find them:
2895 # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
2896 if( $level && $format ) {
2897 $note = "<div id='mw-{$level}{$format}preview'>" . wfMessage( "{$level}{$format}preview" )->text() . "</div>";
2898 } else {
2899 $note = wfMessage( 'previewnote' )->text() ;
2900 }
2901 } else {
2902 $note = wfMessage( 'previewnote' )->text() ;
2903 }
2904
2905 $rt = $content->getRedirectChain();
2906 if ( $rt ) {
2907 $previewHTML = $this->mArticle->viewRedirect( $rt, false );
2908 } else {
2909
2910 # If we're adding a comment, we need to show the
2911 # summary as the headline
2912 if ( $this->section === "new" && $this->summary !== "" ) {
2913 $content = $content->addSectionHeader( $this->summary );
2914 }
2915
2916 $hook_args = array( $this, &$content );
2917 ContentHandler::runLegacyHooks( 'EditPageGetPreviewText', $hook_args );
2918 wfRunHooks( 'EditPageGetPreviewContent', $hook_args );
2919
2920 $parserOptions->enableLimitReport();
2921
2922 # For CSS/JS pages, we should have called the ShowRawCssJs hook here.
2923 # But it's now deprecated, so never mind
2924
2925 $content = $content->preSaveTransform( $this->mTitle, $wgUser, $parserOptions );
2926 $parserOutput = $content->getParserOutput( $this->getArticle()->getTitle(), null, $parserOptions );
2927
2928 $previewHTML = $parserOutput->getText();
2929 $this->mParserOutput = $parserOutput;
2930 $wgOut->addParserOutputNoText( $parserOutput );
2931
2932 if ( count( $parserOutput->getWarnings() ) ) {
2933 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
2934 }
2935 }
2936 } catch ( MWContentSerializationException $ex ) {
2937 $m = wfMessage('content-failed-to-parse', $this->contentModel, $this->contentFormat, $ex->getMessage() );
2938 $note .= "\n\n" . $m->parse();
2939 $previewHTML = '';
2940 }
2941
2942 if ( $this->isConflict ) {
2943 $conflict = '<h2 id="mw-previewconflict">' . wfMessage( 'previewconflict' )->escaped() . "</h2>\n";
2944 } else {
2945 $conflict = '<hr />';
2946 }
2947
2948 $previewhead = "<div class='previewnote'>\n" .
2949 '<h2 id="mw-previewheader">' . wfMessage( 'preview' )->escaped() . "</h2>" .
2950 $wgOut->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
2951
2952 $pageLang = $this->mTitle->getPageLanguage();
2953 $attribs = array( 'lang' => $pageLang->getCode(), 'dir' => $pageLang->getDir(),
2954 'class' => 'mw-content-' . $pageLang->getDir() );
2955 $previewHTML = Html::rawElement( 'div', $attribs, $previewHTML );
2956
2957 wfProfileOut( __METHOD__ );
2958 return $previewhead . $previewHTML . $this->previewTextAfterContent;
2959 }
2960
2961 /**
2962 * @return Array
2963 */
2964 function getTemplates() {
2965 if ( $this->preview || $this->section != '' ) {
2966 $templates = array();
2967 if ( !isset( $this->mParserOutput ) ) {
2968 return $templates;
2969 }
2970 foreach ( $this->mParserOutput->getTemplates() as $ns => $template ) {
2971 foreach ( array_keys( $template ) as $dbk ) {
2972 $templates[] = Title::makeTitle( $ns, $dbk );
2973 }
2974 }
2975 return $templates;
2976 } else {
2977 return $this->mTitle->getTemplateLinksFrom();
2978 }
2979 }
2980
2981 /**
2982 * Shows a bulletin board style toolbar for common editing functions.
2983 * It can be disabled in the user preferences.
2984 * The necessary JavaScript code can be found in skins/common/edit.js.
2985 *
2986 * @return string
2987 */
2988 static function getEditToolbar() {
2989 global $wgStylePath, $wgContLang, $wgLang, $wgOut;
2990 global $wgUseTeX, $wgEnableUploads, $wgForeignFileRepos;
2991
2992 $imagesAvailable = $wgEnableUploads || count( $wgForeignFileRepos );
2993
2994 /**
2995 * $toolarray is an array of arrays each of which includes the
2996 * filename of the button image (without path), the opening
2997 * tag, the closing tag, optionally a sample text that is
2998 * inserted between the two when no selection is highlighted
2999 * and. The tip text is shown when the user moves the mouse
3000 * over the button.
3001 *
3002 * Also here: accesskeys (key), which are not used yet until
3003 * someone can figure out a way to make them work in
3004 * IE. However, we should make sure these keys are not defined
3005 * on the edit page.
3006 */
3007 $toolarray = array(
3008 array(
3009 'image' => $wgLang->getImageFile( 'button-bold' ),
3010 'id' => 'mw-editbutton-bold',
3011 'open' => '\'\'\'',
3012 'close' => '\'\'\'',
3013 'sample' => wfMessage( 'bold_sample' )->text(),
3014 'tip' => wfMessage( 'bold_tip' )->text(),
3015 'key' => 'B'
3016 ),
3017 array(
3018 'image' => $wgLang->getImageFile( 'button-italic' ),
3019 'id' => 'mw-editbutton-italic',
3020 'open' => '\'\'',
3021 'close' => '\'\'',
3022 'sample' => wfMessage( 'italic_sample' )->text(),
3023 'tip' => wfMessage( 'italic_tip' )->text(),
3024 'key' => 'I'
3025 ),
3026 array(
3027 'image' => $wgLang->getImageFile( 'button-link' ),
3028 'id' => 'mw-editbutton-link',
3029 'open' => '[[',
3030 'close' => ']]',
3031 'sample' => wfMessage( 'link_sample' )->text(),
3032 'tip' => wfMessage( 'link_tip' )->text(),
3033 'key' => 'L'
3034 ),
3035 array(
3036 'image' => $wgLang->getImageFile( 'button-extlink' ),
3037 'id' => 'mw-editbutton-extlink',
3038 'open' => '[',
3039 'close' => ']',
3040 'sample' => wfMessage( 'extlink_sample' )->text(),
3041 'tip' => wfMessage( 'extlink_tip' )->text(),
3042 'key' => 'X'
3043 ),
3044 array(
3045 'image' => $wgLang->getImageFile( 'button-headline' ),
3046 'id' => 'mw-editbutton-headline',
3047 'open' => "\n== ",
3048 'close' => " ==\n",
3049 'sample' => wfMessage( 'headline_sample' )->text(),
3050 'tip' => wfMessage( 'headline_tip' )->text(),
3051 'key' => 'H'
3052 ),
3053 $imagesAvailable ? array(
3054 'image' => $wgLang->getImageFile( 'button-image' ),
3055 'id' => 'mw-editbutton-image',
3056 'open' => '[[' . $wgContLang->getNsText( NS_FILE ) . ':',
3057 'close' => ']]',
3058 'sample' => wfMessage( 'image_sample' )->text(),
3059 'tip' => wfMessage( 'image_tip' )->text(),
3060 'key' => 'D',
3061 ) : false,
3062 $imagesAvailable ? array(
3063 'image' => $wgLang->getImageFile( 'button-media' ),
3064 'id' => 'mw-editbutton-media',
3065 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA ) . ':',
3066 'close' => ']]',
3067 'sample' => wfMessage( 'media_sample' )->text(),
3068 'tip' => wfMessage( 'media_tip' )->text(),
3069 'key' => 'M'
3070 ) : false,
3071 $wgUseTeX ? array(
3072 'image' => $wgLang->getImageFile( 'button-math' ),
3073 'id' => 'mw-editbutton-math',
3074 'open' => "<math>",
3075 'close' => "</math>",
3076 'sample' => wfMessage( 'math_sample' )->text(),
3077 'tip' => wfMessage( 'math_tip' )->text(),
3078 'key' => 'C'
3079 ) : false,
3080 array(
3081 'image' => $wgLang->getImageFile( 'button-nowiki' ),
3082 'id' => 'mw-editbutton-nowiki',
3083 'open' => "<nowiki>",
3084 'close' => "</nowiki>",
3085 'sample' => wfMessage( 'nowiki_sample' )->text(),
3086 'tip' => wfMessage( 'nowiki_tip' )->text(),
3087 'key' => 'N'
3088 ),
3089 array(
3090 'image' => $wgLang->getImageFile( 'button-sig' ),
3091 'id' => 'mw-editbutton-signature',
3092 'open' => '--~~~~',
3093 'close' => '',
3094 'sample' => '',
3095 'tip' => wfMessage( 'sig_tip' )->text(),
3096 'key' => 'Y'
3097 ),
3098 array(
3099 'image' => $wgLang->getImageFile( 'button-hr' ),
3100 'id' => 'mw-editbutton-hr',
3101 'open' => "\n----\n",
3102 'close' => '',
3103 'sample' => '',
3104 'tip' => wfMessage( 'hr_tip' )->text(),
3105 'key' => 'R'
3106 )
3107 );
3108
3109 $script = 'mw.loader.using("mediawiki.action.edit", function() {';
3110 foreach ( $toolarray as $tool ) {
3111 if ( !$tool ) {
3112 continue;
3113 }
3114
3115 $params = array(
3116 $image = $wgStylePath . '/common/images/' . $tool['image'],
3117 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
3118 // Older browsers show a "speedtip" type message only for ALT.
3119 // Ideally these should be different, realistically they
3120 // probably don't need to be.
3121 $tip = $tool['tip'],
3122 $open = $tool['open'],
3123 $close = $tool['close'],
3124 $sample = $tool['sample'],
3125 $cssId = $tool['id'],
3126 );
3127
3128 $script .= Xml::encodeJsCall( 'mw.toolbar.addButton', $params );
3129 }
3130
3131 // This used to be called on DOMReady from mediawiki.action.edit, which
3132 // ended up causing race conditions with the setup code above.
3133 $script .= "\n" .
3134 "// Create button bar\n" .
3135 "$(function() { mw.toolbar.init(); } );\n";
3136
3137 $script .= '});';
3138 $wgOut->addScript( Html::inlineScript( ResourceLoader::makeLoaderConditionalScript( $script ) ) );
3139
3140 $toolbar = '<div id="toolbar"></div>';
3141
3142 wfRunHooks( 'EditPageBeforeEditToolbar', array( &$toolbar ) );
3143
3144 return $toolbar;
3145 }
3146
3147 /**
3148 * Returns an array of html code of the following checkboxes:
3149 * minor and watch
3150 *
3151 * @param $tabindex int Current tabindex
3152 * @param $checked Array of checkbox => bool, where bool indicates the checked
3153 * status of the checkbox
3154 *
3155 * @return array
3156 */
3157 public function getCheckboxes( &$tabindex, $checked ) {
3158 global $wgUser;
3159
3160 $checkboxes = array();
3161
3162 // don't show the minor edit checkbox if it's a new page or section
3163 if ( !$this->isNew ) {
3164 $checkboxes['minor'] = '';
3165 $minorLabel = wfMessage( 'minoredit' )->parse();
3166 if ( $wgUser->isAllowed( 'minoredit' ) ) {
3167 $attribs = array(
3168 'tabindex' => ++$tabindex,
3169 'accesskey' => wfMessage( 'accesskey-minoredit' )->text(),
3170 'id' => 'wpMinoredit',
3171 );
3172 $checkboxes['minor'] =
3173 Xml::check( 'wpMinoredit', $checked['minor'], $attribs ) .
3174 "&#160;<label for='wpMinoredit' id='mw-editpage-minoredit'" .
3175 Xml::expandAttributes( array( 'title' => Linker::titleAttrib( 'minoredit', 'withaccess' ) ) ) .
3176 ">{$minorLabel}</label>";
3177 }
3178 }
3179
3180 $watchLabel = wfMessage( 'watchthis' )->parse();
3181 $checkboxes['watch'] = '';
3182 if ( $wgUser->isLoggedIn() ) {
3183 $attribs = array(
3184 'tabindex' => ++$tabindex,
3185 'accesskey' => wfMessage( 'accesskey-watch' )->text(),
3186 'id' => 'wpWatchthis',
3187 );
3188 $checkboxes['watch'] =
3189 Xml::check( 'wpWatchthis', $checked['watch'], $attribs ) .
3190 "&#160;<label for='wpWatchthis' id='mw-editpage-watch'" .
3191 Xml::expandAttributes( array( 'title' => Linker::titleAttrib( 'watch', 'withaccess' ) ) ) .
3192 ">{$watchLabel}</label>";
3193 }
3194 wfRunHooks( 'EditPageBeforeEditChecks', array( &$this, &$checkboxes, &$tabindex ) );
3195 return $checkboxes;
3196 }
3197
3198 /**
3199 * Returns an array of html code of the following buttons:
3200 * save, diff, preview and live
3201 *
3202 * @param $tabindex int Current tabindex
3203 *
3204 * @return array
3205 */
3206 public function getEditButtons( &$tabindex ) {
3207 $buttons = array();
3208
3209 $temp = array(
3210 'id' => 'wpSave',
3211 'name' => 'wpSave',
3212 'type' => 'submit',
3213 'tabindex' => ++$tabindex,
3214 'value' => wfMessage( 'savearticle' )->text(),
3215 'accesskey' => wfMessage( 'accesskey-save' )->text(),
3216 'title' => wfMessage( 'tooltip-save' )->text() . ' [' . wfMessage( 'accesskey-save' )->text() . ']',
3217 );
3218 $buttons['save'] = Xml::element( 'input', $temp, '' );
3219
3220 ++$tabindex; // use the same for preview and live preview
3221 $temp = array(
3222 'id' => 'wpPreview',
3223 'name' => 'wpPreview',
3224 'type' => 'submit',
3225 'tabindex' => $tabindex,
3226 'value' => wfMessage( 'showpreview' )->text(),
3227 'accesskey' => wfMessage( 'accesskey-preview' )->text(),
3228 'title' => wfMessage( 'tooltip-preview' )->text() . ' [' . wfMessage( 'accesskey-preview' )->text() . ']',
3229 );
3230 $buttons['preview'] = Xml::element( 'input', $temp, '' );
3231 $buttons['live'] = '';
3232
3233 $temp = array(
3234 'id' => 'wpDiff',
3235 'name' => 'wpDiff',
3236 'type' => 'submit',
3237 'tabindex' => ++$tabindex,
3238 'value' => wfMessage( 'showdiff' )->text(),
3239 'accesskey' => wfMessage( 'accesskey-diff' )->text(),
3240 'title' => wfMessage( 'tooltip-diff' )->text() . ' [' . wfMessage( 'accesskey-diff' )->text() . ']',
3241 );
3242 $buttons['diff'] = Xml::element( 'input', $temp, '' );
3243
3244 wfRunHooks( 'EditPageBeforeEditButtons', array( &$this, &$buttons, &$tabindex ) );
3245 return $buttons;
3246 }
3247
3248 /**
3249 * Output preview text only. This can be sucked into the edit page
3250 * via JavaScript, and saves the server time rendering the skin as
3251 * well as theoretically being more robust on the client (doesn't
3252 * disturb the edit box's undo history, won't eat your text on
3253 * failure, etc).
3254 *
3255 * @todo This doesn't include category or interlanguage links.
3256 * Would need to enhance it a bit, "<s>maybe wrap them in XML
3257 * or something...</s>" that might also require more skin
3258 * initialization, so check whether that's a problem.
3259 */
3260 function livePreview() {
3261 global $wgOut;
3262 $wgOut->disable();
3263 header( 'Content-type: text/xml; charset=utf-8' );
3264 header( 'Cache-control: no-cache' );
3265
3266 $previewText = $this->getPreviewText();
3267 #$categories = $skin->getCategoryLinks();
3268
3269 $s =
3270 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
3271 Xml::tags( 'livepreview', null,
3272 Xml::element( 'preview', null, $previewText )
3273 #. Xml::element( 'category', null, $categories )
3274 );
3275 echo $s;
3276 }
3277
3278 /**
3279 * Call the stock "user is blocked" page
3280 *
3281 * @deprecated in 1.19; throw an exception directly instead
3282 */
3283 function blockedPage() {
3284 wfDeprecated( __METHOD__, '1.19' );
3285 global $wgUser;
3286
3287 throw new UserBlockedError( $wgUser->getBlock() );
3288 }
3289
3290 /**
3291 * Produce the stock "please login to edit pages" page
3292 *
3293 * @deprecated in 1.19; throw an exception directly instead
3294 */
3295 function userNotLoggedInPage() {
3296 wfDeprecated( __METHOD__, '1.19' );
3297 throw new PermissionsError( 'edit' );
3298 }
3299
3300 /**
3301 * Show an error page saying to the user that he has insufficient permissions
3302 * to create a new page
3303 *
3304 * @deprecated in 1.19; throw an exception directly instead
3305 */
3306 function noCreatePermission() {
3307 wfDeprecated( __METHOD__, '1.19' );
3308 $permission = $this->mTitle->isTalkPage() ? 'createtalk' : 'createpage';
3309 throw new PermissionsError( $permission );
3310 }
3311
3312 /**
3313 * Creates a basic error page which informs the user that
3314 * they have attempted to edit a nonexistent section.
3315 */
3316 function noSuchSectionPage() {
3317 global $wgOut;
3318
3319 $wgOut->prepareErrorPage( wfMessage( 'nosuchsectiontitle' ) );
3320
3321 $res = wfMessage( 'nosuchsectiontext', $this->section )->parseAsBlock();
3322 wfRunHooks( 'EditPageNoSuchSection', array( &$this, &$res ) );
3323 $wgOut->addHTML( $res );
3324
3325 $wgOut->returnToMain( false, $this->mTitle );
3326 }
3327
3328 /**
3329 * Produce the stock "your edit contains spam" page
3330 *
3331 * @param $match string Text which triggered one or more filters
3332 * @deprecated since 1.17 Use method spamPageWithContent() instead
3333 */
3334 static function spamPage( $match = false ) {
3335 wfDeprecated( __METHOD__, '1.17' );
3336
3337 global $wgOut, $wgTitle;
3338
3339 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
3340
3341 $wgOut->addHTML( '<div id="spamprotected">' );
3342 $wgOut->addWikiMsg( 'spamprotectiontext' );
3343 if ( $match ) {
3344 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
3345 }
3346 $wgOut->addHTML( '</div>' );
3347
3348 $wgOut->returnToMain( false, $wgTitle );
3349 }
3350
3351 /**
3352 * Show "your edit contains spam" page with your diff and text
3353 *
3354 * @param $match string|Array|bool Text (or array of texts) which triggered one or more filters
3355 */
3356 public function spamPageWithContent( $match = false ) {
3357 global $wgOut, $wgLang;
3358 $this->textbox2 = $this->textbox1;
3359
3360 if( is_array( $match ) ){
3361 $match = $wgLang->listToText( $match );
3362 }
3363 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
3364
3365 $wgOut->addHTML( '<div id="spamprotected">' );
3366 $wgOut->addWikiMsg( 'spamprotectiontext' );
3367 if ( $match ) {
3368 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
3369 }
3370 $wgOut->addHTML( '</div>' );
3371
3372 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3373 $this->showDiff();
3374
3375 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3376 $this->showTextbox2();
3377
3378 $wgOut->addReturnTo( $this->getContextTitle(), array( 'action' => 'edit' ) );
3379 }
3380
3381 /**
3382 * Format an anchor fragment as it would appear for a given section name
3383 * @param $text String
3384 * @return String
3385 * @private
3386 */
3387 function sectionAnchor( $text ) {
3388 global $wgParser;
3389 return $wgParser->guessSectionNameFromWikiText( $text );
3390 }
3391
3392 /**
3393 * Check if the browser is on a blacklist of user-agents known to
3394 * mangle UTF-8 data on form submission. Returns true if Unicode
3395 * should make it through, false if it's known to be a problem.
3396 * @return bool
3397 * @private
3398 */
3399 function checkUnicodeCompliantBrowser() {
3400 global $wgBrowserBlackList, $wgRequest;
3401
3402 $currentbrowser = $wgRequest->getHeader( 'User-Agent' );
3403 if ( $currentbrowser === false ) {
3404 // No User-Agent header sent? Trust it by default...
3405 return true;
3406 }
3407
3408 foreach ( $wgBrowserBlackList as $browser ) {
3409 if ( preg_match( $browser, $currentbrowser ) ) {
3410 return false;
3411 }
3412 }
3413 return true;
3414 }
3415
3416 /**
3417 * Filter an input field through a Unicode de-armoring process if it
3418 * came from an old browser with known broken Unicode editing issues.
3419 *
3420 * @param $request WebRequest
3421 * @param $field String
3422 * @return String
3423 * @private
3424 */
3425 function safeUnicodeInput( $request, $field ) {
3426 $text = rtrim( $request->getText( $field ) );
3427 return $request->getBool( 'safemode' )
3428 ? $this->unmakesafe( $text )
3429 : $text;
3430 }
3431
3432 /**
3433 * @param $request WebRequest
3434 * @param $text string
3435 * @return string
3436 */
3437 function safeUnicodeText( $request, $text ) {
3438 $text = rtrim( $text );
3439 return $request->getBool( 'safemode' )
3440 ? $this->unmakesafe( $text )
3441 : $text;
3442 }
3443
3444 /**
3445 * Filter an output field through a Unicode armoring process if it is
3446 * going to an old browser with known broken Unicode editing issues.
3447 *
3448 * @param $text String
3449 * @return String
3450 * @private
3451 */
3452 function safeUnicodeOutput( $text ) {
3453 global $wgContLang;
3454 $codedText = $wgContLang->recodeForEdit( $text );
3455 return $this->checkUnicodeCompliantBrowser()
3456 ? $codedText
3457 : $this->makesafe( $codedText );
3458 }
3459
3460 /**
3461 * A number of web browsers are known to corrupt non-ASCII characters
3462 * in a UTF-8 text editing environment. To protect against this,
3463 * detected browsers will be served an armored version of the text,
3464 * with non-ASCII chars converted to numeric HTML character references.
3465 *
3466 * Preexisting such character references will have a 0 added to them
3467 * to ensure that round-trips do not alter the original data.
3468 *
3469 * @param $invalue String
3470 * @return String
3471 * @private
3472 */
3473 function makesafe( $invalue ) {
3474 // Armor existing references for reversability.
3475 $invalue = strtr( $invalue, array( "&#x" => "&#x0" ) );
3476
3477 $bytesleft = 0;
3478 $result = "";
3479 $working = 0;
3480 for ( $i = 0; $i < strlen( $invalue ); $i++ ) {
3481 $bytevalue = ord( $invalue[$i] );
3482 if ( $bytevalue <= 0x7F ) { // 0xxx xxxx
3483 $result .= chr( $bytevalue );
3484 $bytesleft = 0;
3485 } elseif ( $bytevalue <= 0xBF ) { // 10xx xxxx
3486 $working = $working << 6;
3487 $working += ( $bytevalue & 0x3F );
3488 $bytesleft--;
3489 if ( $bytesleft <= 0 ) {
3490 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
3491 }
3492 } elseif ( $bytevalue <= 0xDF ) { // 110x xxxx
3493 $working = $bytevalue & 0x1F;
3494 $bytesleft = 1;
3495 } elseif ( $bytevalue <= 0xEF ) { // 1110 xxxx
3496 $working = $bytevalue & 0x0F;
3497 $bytesleft = 2;
3498 } else { // 1111 0xxx
3499 $working = $bytevalue & 0x07;
3500 $bytesleft = 3;
3501 }
3502 }
3503 return $result;
3504 }
3505
3506 /**
3507 * Reverse the previously applied transliteration of non-ASCII characters
3508 * back to UTF-8. Used to protect data from corruption by broken web browsers
3509 * as listed in $wgBrowserBlackList.
3510 *
3511 * @param $invalue String
3512 * @return String
3513 * @private
3514 */
3515 function unmakesafe( $invalue ) {
3516 $result = "";
3517 for ( $i = 0; $i < strlen( $invalue ); $i++ ) {
3518 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue[$i + 3] != '0' ) ) {
3519 $i += 3;
3520 $hexstring = "";
3521 do {
3522 $hexstring .= $invalue[$i];
3523 $i++;
3524 } while ( ctype_xdigit( $invalue[$i] ) && ( $i < strlen( $invalue ) ) );
3525
3526 // Do some sanity checks. These aren't needed for reversability,
3527 // but should help keep the breakage down if the editor
3528 // breaks one of the entities whilst editing.
3529 if ( ( substr( $invalue, $i, 1 ) == ";" ) and ( strlen( $hexstring ) <= 6 ) ) {
3530 $codepoint = hexdec( $hexstring );
3531 $result .= codepointToUtf8( $codepoint );
3532 } else {
3533 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
3534 }
3535 } else {
3536 $result .= substr( $invalue, $i, 1 );
3537 }
3538 }
3539 // reverse the transform that we made for reversability reasons.
3540 return strtr( $result, array( "&#x0" => "&#x" ) );
3541 }
3542 }